Clone div if it overflows parent bottom to other div - javascript

I'm making an A4-print template for WP, and I want it to dynamically create new pages when content overflows. So my plan is to target each child div that has an offset greater than the parents .top + height();. Note: I use the self.css('color','red'); to check that the function is working.
With this code below I get an error:
copyCon is not defined
function newPage() {
if ($(this).height() > a4Height) {
offObject.each(function() {
var self = $(this);
var offObjectWrap = self.parent().parent().parent('.docWrap');
var wrapBottom = offObjectWrap.offset().top + offObjectWrap.height();
var selfPos = self.offset().top + self.height();
if (selfPos > wrapBottom) {
var copyCon = $(this).clone();
} else {
self.css('color', 'red');
}
});
var copyFooter = $(".offerFooter").clone();
$(this).parent().parent().after('<section id="page4" class="offerPage docWrap pageTwo clearfix"><div class="docPad clearfix"><div class="docCon clearfix">' + copyCon.html() + '</div></div><div class="offerFooter clearfix">' + copyFooter.html() + "</div></section>");
}
}
docCon.each(newPage);

Related

Image Resizer - issue to drag an image into a div

I want to make a little program where we can :
- Drag and drop an image into a Div (from desktop to the div of the web page)
- Drag the image into this div
- Zoom in and zoom out whit the mouse wheel.
what id did is drag and drop an image and its work..
i set an id of the image in my Javascript code and in my console i see that the image receive the id='movable'.. But when i test that in my browser the image doesnt move with my mouse.
Here is my Javascript Code :
//Creation d'un DIV dynamique
monDiv = document.createElement("div");
monDiv.id = 'dropZone';
monDiv.innerHTML = '<h4>Glissez deposez une image</h4>';
document.body.appendChild(monDiv);
//Drag And Drop
(function(window) {
function triggerCallback(e, callback) {
if(!callback || typeof callback !== 'function') {
return;
}
var files;
if(e.dataTransfer) {
files = e.dataTransfer.files;
} else if(e.target) {
files = e.target.files;
}
callback.call(null, files);
}
function makeDroppable(ele, callback) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('multiple', true);
input.style.display = 'none';
input.addEventListener('change', function(e) {
triggerCallback(e, callback);
});
ele.appendChild(input);
ele.addEventListener('dragover', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.add('dragover');
});
ele.addEventListener('dragleave', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.remove('dragover');
});
ele.addEventListener('drop', function(e) {
e.preventDefault();
e.stopPropagation();
ele.classList.remove('dragover');
triggerCallback(e, callback);
});
}
window.makeDroppable = makeDroppable;
})(this);
(function(window) {
makeDroppable(window.document.querySelector('#dropZone'), function(files) {
console.log(files);
var output = document.querySelector('#dropZone');
output.innerHTML = '';
for(var i=0; i<files.length; i++) {
if(files[i].type.indexOf('image/') === 0) {
output.innerHTML += '<img src="' + URL.createObjectURL(files[i]) + '" id="movable" />';
}
}
});
})(this);
//DRAG
$('#movable').on('mousedown', function (e) {
$(this).addClass('active');
var oTop = e.pageY - $('.active').offset().top;
var oLeft = e.pageX - $('.active').offset().left;
$(this).parents().on('mousemove', function (e) {
$('.active').offset({
top: e.pageY - oTop,
left: e.pageX - oLeft
});
});
$(this).on('mouseup', function () {
$(this).removeClass('active');
});
return false;
});
Increase image ration on scroll up and decrease it on scroll down.
zoomIn: function ()
{
image.ratio*=1.1;
createBackground();
},
zoomOut: function ()
{
image.ratio*=0.9;
createBackground();
}
createBackground = function()
{
var w = parseInt(image.width)*image.ratio;
var h = parseInt(image.height)*image.ratio;
//Element in which image is available
var pw = (el.clientWidth - w) / 2;
var ph = (el.clientHeight - h) / 2;
el.setAttribute('style',
'background-image: url(' +image.src + '); ' +
'background-size: ' + w +'px ' + h + 'px; ' +
'background-position: ' + pw + 'px ' + ph + 'px; ' +
'background-repeat: no-repeat');
},
I just figured out.. I place my jQuery code inside the makeDroppable function and the image move inside my div and add overflow:hidden in my css
(function(window) {
makeDroppable(window.document.querySelector('#dropZone'), function(files) {
console.log(files);
var output = document.querySelector('#dropZone');
output.innerHTML = '';
for(var i=0; i<files.length; i++) {
if(files[i].type.indexOf('image/') === 0) {
output.innerHTML += '<img src="' + URL.createObjectURL(files[i]) + '" id="movable" />';
//DRAG
$( "#movable" ).draggable();
}
}
});
})(this);

I'm not sure why my click event won't work

I'm trying to add a click event to .user that will change the background color of the entire page to green. I'm very new to jQuery, but the code looks right to me. When I click the .users button, nothing happens. Anyone have any ideas?
$(document).ready(function() {
var $body = $('body')
/*$body.html('');*/
// var currentView = "Twittler Feed"
var currentView = $('<p>Twittler Feed</p>');
var refreshTweet = function() {
var index = streams.home.length - 1;
var endInd = index - 10;
while (index >= endInd) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweets"><p class="posted-by"><button class="user">#' +
tweet.user + '</button><p class="message">' + tweet.message +
'</p><p class="time">' + /*$.timeago(tweet.created_at)*/ tweet.created_at + '</p></div>');
currentView.appendTo('#sidebar')
$tweet.appendTo($body);
index -= 1;
}
}
refreshTweet();
$('.refresh').on('click', function() {
if (document.getElementsByClassName('tweets')) {
$('.tweets').remove();
}
var result = refreshTweet();
$body.prepend(result);
})
$('.user').on('click', 'button', function() {
currentView = this.user
$('body').css('background-color', 'green');
});
});

Highcharts Bar Chart not printing correctly

I have a bar chart using Highcharts. On the screen it looks like this:
But when I go to print it looks like this:
So basically nothing is showing up when I go to print. Here is the javascript I am using.
function qm_load_barcharts(qmsr_data) {
var bar_width = 200;
$('#profile-barchart tbody tr').each(function() {
$(this).children('td').eq(4).each(function() {
// Get the div id.
var $div_id = $(this).children('div').eq(0).attr('id');
// From the div id reconstitute the pfx in proper form.
var pfx = $div_id.replace(/^x/, '');
pfx = pfx.replace(/_/g, '.');
pfx = pfx.replace(/-/, '/');
// Look up our indicator values for the prefix.
var active_cnt = qmsr_data[pfx]['active'];
var latent_cnt = qmsr_data[pfx]['latent'];
var indicators_cnt = qmsr_data[pfx]['indicators'];
// Set our bar segment sizes.
var total = active_cnt + latent_cnt + indicators_cnt;
var active_size;
var latent_size;
var indicators_size;
if (active_cnt == 0) {
active_size = 0;
}
else {
active_size = Math.round((active_cnt/total) * bar_width);
}
if (latent_cnt == 0) {
latent_size = 0;
}
else {
latent_size = Math.round((latent_cnt/total) * bar_width);
}
if (indicators_cnt == 0) {
indicators_size = 0;
}
else {
indicators_size = Math.round((indicators_cnt/total) * bar_width);
}
if ((active_cnt + latent_cnt + indicators_cnt) == 0) {
// Perfect score, so make one full-width gray bar.
$('#' + $div_id).children('div.active-bar').eq(0).css("background-color", "#ababab");
$('#' + $div_id).children('div').eq(0).width(bar_width + 'px');
$('#' + $div_id).children('div').eq(1).width('0px');
$('#' + $div_id).children('div').eq(2).width('0px');
}
else {
// Set div sizes proportionately.
$('#' + $div_id).children('div').eq(0).width(active_size + 'px');
$('#' + $div_id).children('div').eq(1).width(latent_size + 'px');
$('#' + $div_id).children('div').eq(2).width(indicators_size + 'px');
// Set values inside dives.
$('#' + $div_id).children('div.active-bar').children('div').eq(0).html(active_cnt);
$('#' + $div_id).children('div.latent-bar').children('div').eq(0).html(latent_cnt);
$('#' + $div_id).children('div.indicators-bar').children('div').eq(0).html(indicators_cnt);
}
});
});
}
Here's the HTML:
<div id="<%= $pfx_id %>" class='qmsr-barchart'>
<div class='active-bar'>
<div class='hidden-nugget'></div>
</div>
<div class='latent-bar'>
<div class='hidden-nugget'></div>
</div>
<div class='indicators-bar'>
<div class='hidden-nugget'></div>
</div>
</div>
And here's the print view CSS:
#media print {
.active-bar {
background-color: #A74A44;
}
.latent-bar {
background-color: #EB8104;
}
.indicators-bar {
background-color: #E6E714;
}
}
I am trying to print it in Chrome, if that matters at all.

Building css properties via javascript events

I'm trying to display an arrow which guides the user to the top of the page on click:
html code
<a id="top" href="#"><img src="/img/arrow.png"></a>
css code
.scroll #top{
opacity: .2;
}
js code
o = $;
// misc junk
o(function(){
var width = window.innerWidth;
var height = window.innerHeight;
var doc = o(document);
// .onload
o('html').addClass('onload');
// top link
o('#top').click(function(e){
o('body').animate({ scrollTop: 0 }, 'fast');
e.preventDefault();
});
// scrolling links
var added;
doc.scroll(function(e){
if (doc.scrollTop() > 5) {
if (added) return;
added = true;
o('body').addClass('scroll');
} else {
o('body').removeClass('scroll');
added = false;
}
})
// highlight code
o('pre.js code').each(function(){
o(this).html(highlight(o(this).text()));
})
})
// active menu junk
o(function(){
var prev;
var n = 0;
var headings = o('h3').map(function(i, el){
return {
top: o(el).offset().top,
id: el.id
}
});
function closest() {
var h;
var top = o(window).scrollTop();
var i = headings.length;
while (i--) {
h = headings[i];
if (top >= h.top - 1) return h;
}
}
o(document).scroll(function(){
var h = closest();
if (!h) return;
if (prev) {
prev.removeClass('active');
prev.parent().parent().removeClass('active');
}
var a = o('a[href="#' + h.id + '"]');
a.addClass('active');
a.parent().parent().addClass('active');
prev = a;
})
})
/**
* Highlight the given `js`.
*/
function highlight(js) {
return js
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
.replace(/('.*?')/gm, '<span class="string">$1</span>')
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
.replace(/(\d+)/gm, '<span class="number">$1</span>')
.replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>')
}
Setting this in place, wouldn't makes appear the arrow on scroll of page. How to fix this, please ?

removing function on click jquery

I have gone through quite a few similar question but none of them fit to my problem.
I am calling a function after onclick event to my anchor tag and after clicking the anchor tag the function adds a row new row to another section within the webpage.
What I am trying to do is to revert the process back when a user clicks on the same anchor tag again. In other words the newly added row should be removed from the view if clicked again.
Here is my code where on click I am calling a function to add new rows
function drawSelections(betTypeId, tableId, selections) {
var whiteLegendTrId = tableId + '_whiteLegendTr';
$.each(selections, function(i, v){
var selectionRowId = tableId + '_' + v.id;
document.getElementById(tableId).appendChild(createTr(selectionRowId,null,"white"));
$('#' + whiteLegendTrId).find('td').each(function() {
var tdId = $(this).attr('id');
if (tdId == "pic") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, "",null))}
else if (tdId == "no") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.position,null))}
else if (tdId == "horseName" || tdId == "jockey") {document.getElementById(selectionRowId).appendChild(createTd(null, null, null, v.name,null))}
// Horse prices
else {
var priceNotFound = true;
$.each(v.prices, function(index,value) {
if (value.betTypeId == betTypeId && (value.productId == tdId || value.betTypeId == tdId)) {
priceNotFound = false;
var td = createTd(null, null, null, "", null),
a = document.createElement('a');
a.innerHTML = value.value.toFixed(2);
// adding new rows after onclick to anchore tag
(function(i, index){
a.onclick=function() {
var betInfo = createMapForBet(selections[i],index);
$(this).toggleClass("highlight");
increaseBetSlipCount();
addToSingleBetSlip(betInfo);
}
})(i,index)
td.appendChild(a);
document.getElementById(selectionRowId).appendChild(td);
}
});
if (priceNotFound) document.getElementById(selectionRowId).appendChild(createTd(null, null, null, '-',null));
};
});
});
}
Adding new rows
function addToSingleBetSlip(betInfo) {
// Show bet slip
$('.betslip_details.gray').show();
// Make Single tab active
selectSingleBetSlip();
// Create div for the bet
var div = createSingleBetDiv(betInfo);
$("#bets").append(div);
// Increase single bet counter
updateBetSinglesCounter();
}
This is the JS code where I am generating the views for the dynamic rows added after clicking the anchor tag in my first function
function createSingleBetDiv(betInfo) {
var id = betInfo.betType + '_' + betInfo.productId + '_' + betInfo.mpid,
div = createDiv(id + '_div', 'singleBet', 'bet gray2'),
a = createA(null, null, null, 'right orange'),
leftDiv = createDiv(null, null, 'left'),
closeDiv = createDiv(null, null, 'icon_shut_bet'),
singleBetNumber = ++document.getElementsByName('singleBet').length;
// Info abt the bet
$(leftDiv).append('<p class="title"><b><span class="bet_no">' + singleBetNumber + '</span>. ' + betInfo['horseName'] + '</b></p>');
var raceInfo = "";
$("#raceInfo").contents().filter(function () {
if (this.nodeType === 3) raceInfo = $(this).text() + ', ' + betInfo['betTypeName'] + ' (' + betInfo['value'].toFixed(2) + ')';
});
$(leftDiv).append('<p class="title">' + raceInfo + '</p>');
// Closing btn
(function(id) {
a.onclick=function() {
removeSingleBet(id + '_div');
};
})(id);
$(a).append(closeDiv);
// Creating input field
$(leftDiv).append('<p class="supermid"><input id="' + id + '_input\" type="text"></p>');
// Creating WIN / PLACE checkbox selection
$(leftDiv).append('<p><input id="' + id + '_checkbox\" type="checkbox"><b>' + winPlace + '</b></p>');
// Append left part
$(div).append(leftDiv);
// Append right part
$(div).append(a);
// Appending div with data
$.data(div, 'mapForBet', betInfo);
return div;
}
Function to delete the individual rows
function removeSingleBet(id) {
// Remove the div
removeElement(id);
// Decrease the betslip counter
decreaseBetSlipCount();
// Decrease bet singles counter
updateBetSinglesCounter();
}
function removeElement(id) {
var element = document.getElementById(id);
element.parentNode.removeChild(element);
}
It's not the most elegant solution, but it should get you started.
I tried keeping it in the same format as your code where applicable:
http://jsfiddle.net/L5wmz/
ul{
min-height: 100px;
width: 250px;
border: 1px solid lightGrey;
}
<ul id="bets">
<li id="bet_one">one</li>
<li id="bet_two">two</li>
</ul>
$(document).ready(function(){
var bets = $("#bets li");
var slips = $("#slips");
bets.bind("click", function(){
var that = $(this);
try{
that.data("slipData");
}catch(err){
that.data("slipData",null);
}
if(that.data("slipData") == null){
var slip = createSlip({slipdata:"data"+that.attr("id")});
slip.bind("click", function(){
that.data("slipData",null);
$(this).remove()
});
that.data("slipData",slip);
slips.append(slip);
}
else{
slips.find(that.data("slipData")).remove();
that.data("slipData",null);
}
console.log(that.data("slipData"));
});
});
function createSlip(data){
var item = $(document.createElement("li")).append("slip: "+data.slipdata);
return item;
}

Categories