Highcharts Bar Chart not printing correctly - javascript

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.

Related

How to animate circular progress bar on page scroll down

I have a circular progress bar that animates when the page loads, but I want it to animate when the user scrolls down to it, as it will be in the middle of the page. Right now if the page loads, the user does not see the animation.
So essentially, the animation should be paused until the user scrolls down to a certain point, once the bar is in view, the animation starts.
I used this jquery plugin https://www.jqueryscript.net/loading/jQuery-Plugin-SVG-Progress-Circle.html
function makesvg(percentage, inner_text = "") {
var abs_percentage = Math.abs(percentage).toString();
var percentage_str = percentage.toString();
var classes = ""
if (percentage < 0) {
classes = "danger-stroke circle-chart__circle--negative";
} else if (percentage > 0 && percentage <= 30) {
classes = "warning-stroke";
} else {
classes = "success-stroke";
}
var svg = '<svg class="circle-chart" viewbox="0 0 33.83098862 33.83098862"
xmlns = "http://www.w3.org/2000/svg" > ' +
'<circle class="circle-chart__background" cx="16.9" cy="16.9" r="15.9" / >
' +
'<circle class="circle-chart__circle ' + classes + '"' +
'stroke-dasharray="' + abs_percentage + ',100" cx="16.9" cy="16.9"
r = "15.9" / > ' +
'<g class="circle-chart__info">' +
' <text style="color:#fff;" class="circle-chart__percent" x="17.9"
y = "15.5" > '+percentage_str+' % < /text>';
if (inner_text) {
svg += '<text class="circle-chart__subline" x="16.91549431"
y = "22" > '+inner_text+' < /text>'
}
svg += ' </g></svg>';
return svg
}
(function($) {
$.fn.circlechart = function() {
this.each(function() {
var percentage = $(this).data("percentage");
var inner_text = $(this).text();
var inner_text2 = $(this).text();
$(this).html(makesvg(percentage, inner_text));
});
return this;
};
});
$('.circlechart').circlechart(); // Initialization
Checkout answer of Dan
With reference to answer of Dan, I am adding code that you can use to start/stop animation of circular progress bar
function onVisibilityChange(el, callback) {
var old_visible;
return function () {
var visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
if (typeof callback == 'function') {
callback(visible);
}
}
}
}
var percentage = 0;
var handler = onVisibilityChange(el, function(visiblity_status) {
/* your code go here */
if (visibility_status) {
if (percentage == 0) {
$('.circlechart').circlechart();
} else {
// Code to resume progress bar if there is any method defined for the plugin you are using.
}
} else {
// Code to stop progress bar if there is any method to stop it.
}
});
//jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);

jquery Multiple text scroll on div hover not work

I have This Code for scroll text on hover div using jQuery:
HTML:
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
JS:
$(function()
{
$(".tooMuchText1").hoverForMore({
"speed": 300,
"loop": false,
"target":'#target'
});
});
CSS:
.tooMuchText {
overflow: hidden;
white-space: nowrap;
display: block;
text-align: left;
text-overflow: ellipsis;
cursor: default;
}
So, I need to Scroll multiple(for each) div text on hover with target id. But My code Work only in first div with target id. how do can I fox this problem ?!
Demo jsfiddle
This is just example can you try multiple class in div ? if yes than i have try this in js fiddle please check.. if it may help you
(function($, window) {
var isjQuery = !!$.fn.jquery;
var isFirefox = /Firefox/.test(navigator.userAgent);
var isMobile = /Mobile/.test(navigator.userAgent);
var defaults = {
"speed": 60.0,
"gap": 20,
"loop": true,
"removeTitle": true,
"snapback": true,
"alwaysOn": false,
"addStyles": true,
"target": true,
"startEvent": isMobile ? "touchstart" : (isjQuery ? "mouseenter" : "mouseover"),
"stopEvent": isMobile ? "touchend" : (isjQuery ? "mouseleave" : "mouseout")
};
$.fn['hoverForMore'] = function(options) {
var self = this;
var head = document.getElementsByTagName('head')[0];
var originalOverflow, originalOverflowParent, startTime;
options = $.extend({}, defaults, options);
var targetSelector = options.target || self.selector;
// Always-on without looping is just silly
if (options.alwaysOn) {
options.loop = true;
options.startEvent = "startLooping"; // only triggered programmatically
}
// Detect CSS prefix and presence of CSS animation
var hasAnimation = document.body.style.animationName ? true : false,
animationString = 'animation',
transitionString = 'transition',
transformString = 'transform',
keyframePrefix = '',
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
pfx = '';
// Find the CSS prefix, if necessary
if (hasAnimation === false)
for (var i = 0; i < domPrefixes.length; i++) {
if (document.body.style[domPrefixes[i] + 'AnimationName'] === undefined)
continue;
pfx = domPrefixes[i];
animationString = pfx + 'Animation';
transitionString = pfx + 'Transition';
transformString = pfx + 'Transform';
cssPrefix = '-' + pfx.toLowerCase() + '-';
hasAnimation = true;
break;
}
// Auto-add ellipsis and such
if (options.addStyles) {
head.appendChild($(
'<style type="text/css">' + self.selector + '{' + 'cursor:default;' + 'text-align:left;' + 'display:block;' + 'overflow:hidden;' + 'white-space:nowrap;' + 'text-overflow:ellipsis;' + cssPrefix + 'user-select: none;' + '}</style>')[0]);
}
// Non-animation fallback. TODO: Animate with jQuery instead
if (!hasAnimation) {
// Fallback to title text hover
$(options.target || self.selector).each(function(n, el) {
var $el = $(el);
$el.attr("title", $.trim($el.text()));
});
return self;
}
// Keyframes are only used in loop mode
if (options.loop) {
// Attach global style
var $keyframeStyle = $('<style type="text/css"></style>');
var $keyframeStyleReverse = $('<style type="text/css"></style>');
head.appendChild($keyframeStyle[0]);
head.appendChild($keyframeStyleReverse[0]);
}
// For non-loop mode, set an empty transform value (FireFox needs this to transition properly)
else {
$(self.selector).each(function(n, el) {
el.style[transformString] = 'translateX(0px)';
});
}
// Attach start event
$(targetSelector).on(options.startEvent, function(e) {
startTime = (new Date()).getTime();
// Get hovered item, and ensure that it contains an overflown item
var $item = $(options.target ? self.selector : this).filter(":first");
if (!$item.length) return true;
var $parent = $item.parent();
var pixelDiff = $item[0].scrollWidth - $item.width();
if (pixelDiff <= 0) // && !options.alwaysOn // TODO: <marquee> without overflow
return true;
if (options.removeTitle) $item.removeAttr("title");
// Over-ride the text overflow, and cache the overflow css that we started with
originalOverflowParent = originalOverflowParent || $parent.css("overflow");
originalOverflow = originalOverflow || $item.css("overflow");
$parent.css("overflow", "hidden");
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", "none");
$item
.css("overflow", "visible")
.addClass("scrolling");
if (options.loop) {
// Remove a previous clone
$item.children(".hoverForMoreContent").remove();
// Attach a duplicate string which will allow content to appear wrapped
var $contentClone = $('<span class="hoverForMoreContent" />')
.css({
"paddingLeft": parseInt(options.gap) + "px"
})
.text($item.text());
$item.append($contentClone);
var contentWidth = ($contentClone.width() + parseInt(options.gap));
// Build keyframe string and attach to global style
var keyframes = '#' + cssPrefix + 'keyframes hoverForMoreSlide { ' + 'from {' + cssPrefix + 'transform:translateX( 0 ) }' + 'to {' + cssPrefix + 'transform:translateX( -' + contentWidth + 'px ) }' + '}';
$keyframeStyle[0].innerHTML = keyframes;
// Go go gadget animation!
var sec = contentWidth / parseFloat(options.speed);
$item[0].style[animationString] = 'hoverForMoreSlide ' + sec + 's linear infinite';
} else // if(!options.loop)
{
var sec = pixelDiff / parseFloat(options.speed);
// Apply transition + transform instead of looping
$item[0].style[transitionString] = cssPrefix + 'transform ' + sec + 's linear';
// Alas, Firefox won't honor the transition immediately
if (!isFirefox)
$item[0].style[transformString] = 'translateX(-' + pixelDiff + 'px)';
else setTimeout(function() {
$item[0].style[transformString] = 'translateX(-' + pixelDiff + 'px)';
}, 0);
}
});
// Attach stop event
if (!options.alwaysOn)
$(targetSelector).on(options.stopEvent, function(e) {
var $item = $(options.target ? self.selector : this).filter(":first");
if (!$item.length) return true;
if (options.loop) {
if (options.snapback) {
// Reverse our animation
var contentWidth = $item.children('.hoverForMoreContent').width() + parseInt(options.gap);
var timeDiff = ((new Date()).getTime() - startTime) * 0.001;
var offsetX = (timeDiff * options.speed) % contentWidth;
var switchDirection = offsetX > (contentWidth / 2);
// Build keyframe string and attach to global style
var keyframes = '#' + cssPrefix + 'keyframes hoverForMoreSlideReverse { ' + 'from {' + cssPrefix + 'transform:translateX( ' + (0 - offsetX) + 'px ) }' + 'to {' + cssPrefix + 'transform:translateX( ' + (switchDirection ? 0 - contentWidth : 0) + 'px ) }' + '}';
$keyframeStyleReverse[0].innerHTML = keyframes;
var sec = (switchDirection ? contentWidth - offsetX : offsetX) * 0.2 / parseFloat(options.speed);
$item[0].style[animationString] = 'hoverForMoreSlideReverse ' + (sec > 1 ? 1 : sec) + 's linear';
$item.removeClass("scrolling");
// After animation resolves, restore original overflow setting, and remove the cloned element
setTimeout(function() {
if ($item.is(".scrolling")) return;
$item
.children(".hoverForMoreContent")
.remove();
$item.css("overflow", originalOverflow);
$item.parent().css("overflow", originalOverflowParent);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}, (sec * 1000) - -50);
} else // if(!options.snapback)
{
$item[0].style[animationString] = '';
$item
.css("overflow", originalOverflow)
.find(".hoverForMoreContent")
.remove();
$item.parent().css("overflow", originalOverflowParent);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}
} else // if(!options.loop)
{
var timeDiff = ((new Date()).getTime() - startTime) / 1000.0;
var match = $item[0].style[transitionString].match(/transform (.*)s/);
var sec = (match && match[1] && parseFloat(match[1]) < timeDiff) ? parseFloat(match[1]) : timeDiff;
sec *= 0.5;
if (!options.snapback)
$item[0].style[transitionString] = '';
else
$item[0].style[transitionString] = cssPrefix + 'transform ' + sec + 's linear';
$item.removeClass("scrolling")
// Firefox needs a delay for the transition to take effect
if (!isFirefox)
$item[0].style[transformString] = 'translateX(0px)';
else setTimeout(function() {
$item[0].style[transformString] = 'translateX(0px)';
}, 0);
if (!options.snapback) {
$item.css("overflow", originalOverflow);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
} else // if(options.snapback)
{
setTimeout(function() {
if ($item.is(".scrolling")) return;
$item.css("overflow", originalOverflow);
if (isMobile && options.addStyles)
$('body').css(cssPrefix + "user-select", 'text');
}, sec * 1000);
}
}
});
// To manually refresh active elements when in always-on mode
self.refresh = function() {
$(self.selector).each(function(n, el) {
$(el).not(".scrolling").trigger(options.startEvent);
})
};
// Always-on mode, activate! <marquee>, eat your heart out.
if (options.alwaysOn)
self.refresh();
return self;
};
})(window.jQuery || $);
$(function() {
$(".tooMuchText1").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target'
});
$(".tooMuchText2").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target1'
});
$(".tooMuchText3").hoverForMore({
"speed": 300,
"loop": false,
"target": '#target2'
});
});
.tooMuchText {
overflow: hidden;
white-space: nowrap;
display: block;
text-align: left;
text-overflow: ellipsis;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="target" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText1">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target1" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText2">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
<br>
<div id="target2" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span class="tooMuchText tooMuchText3">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>
<br>
There is at least one conceptual problem here:
id's should always be unique - for identical items, use classes
There are obviously more elegant ways to do this, but latching onto your use of id's, you can expand that, and iterate through the spans, gather their unique ID, then grab the unique ID of the parent, using that as the target.
$(function() {
$(".tooMuchText").each(function() {
var thisParentId = $(this).parents("div").attr("id");
var thisId = $(this).attr("id");
$('#' + thisId).hoverForMore({
"speed": 300,
"loop": false,
"target": '#' + thisParentId
});
});
});
To finish this up, just add a unique id to each of your SPANs and DIVs.
<div id="target3" style="width: 300px;height:100px; margin-left: 50px; background-color: #ddd;">
<span id='tooMuchText3' class="tooMuchText">Got too much text to fit in your content area? Just hover for more more more more more more!</span>
</div>

Clone div if it overflows parent bottom to other div

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);

Ajax Code that loads images on click next and previous for any kind of image silder that has huge no of Images using jsp

I have one slider that works perfectly ..... but the images are loaded at the time of page load ...
I want to load the images on click because I have lot of images to display so I can't load it my homepage because the page takes time to load so I have to use Ajax that loads one image
and and append it to my list
can any body help me how to do it ...
here is the code .. its working ..
the java script part
(function($){
$.fn.imageSlider = function(options) {
var options = $.extend({
leftBtn: '.leftBtn',
rightBtn: '.rightBtn',
visible: 3,
autoPlay: false, // true or false
autoPlayDelay: 10 // delay in seconds
}, options);
var make = function() {
$(this).css('overflow', 'hidden');
var thisWidth = $(this).width();
var mod = thisWidth % options.visible;
if (mod) {
$(this).width(thisWidth - mod); // to prevent bugs while scrolling to the end of slider
}
var el = $(this).children('ul');
el.css({
position: 'relative',
left: '0'
});
var leftBtn = $(options.leftBtn), rightBtn = $(options.rightBtn);
var sliderFirst = el.children('li').slice(0, options.visible);
var tmp = '';
sliderFirst.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderFirst = tmp;
var sliderLast = el.children('li').slice(-options.visible);
tmp = '';
sliderLast.each(function(){
tmp = tmp + '<li>' + $(this).html() + '</li>';
});
sliderLast = tmp;
var elRealQuant = el.children('li').length;
el.append(sliderFirst);
el.prepend(sliderLast);
var elWidth = el.width()/options.visible;
el.children('li').css({
float: 'left',
width: elWidth
});
var elQuant = el.children('li').length;
el.width(elWidth * elQuant);
el.css('left', '-' + elWidth * options.visible + 'px');
function disableButtons() {
leftBtn.addClass('inactive');
rightBtn.addClass('inactive');
}
function enableButtons() {
leftBtn.removeClass('inactive');
rightBtn.removeClass('inactive');
}
leftBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '+=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '0px') {$(this).css('left', '-' + elWidth * elRealQuant + 'px');}
enableButtons();
}
);
}
return false;
});
rightBtn.click(function(event){
event.preventDefault();
if (!$(this).hasClass('inactive')) {
disableButtons();
el.animate({left: '-=' + elWidth + 'px'}, 400,
function(){
if ($(this).css('left') == '-' + (elWidth * (options.visible + elRealQuant)) + 'px') {$(this).css('left', '-' + elWidth * options.visible + 'px');}
enableButtons();
}
);
}
return false;
});
if (options.autoPlay) {
function aPlay() {
rightBtn.click();
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
var delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
el.hover(
function() {
clearTimeout(delId);
},
function() {
delId = setTimeout(aPlay, options.autoPlayDelay * 1000);
}
);
}
};
return this.each(make);
};
})(jQuery);
here is the html
<div class="slider-wrap">
<div class="slider">
<ul id="imgList" class="sliderList">
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
<li><img><src></li>
</ul>
</div>
<img src="/evfimages/prevLogo.png"/>
<img src="/evfimages/nextLogo.png"/>
This is the function that call Js File .
jQuery('.slider').imageSlider({
leftBtn: '.sa-left',
rightBtn: '.sa-right',
visible: 5,
});
And some CSS for formatting
So I have a large no of Images 500 .... so i want to use ajax that loads images on click and append to the current list of images ......
any link or suggestion will be appreciated ......

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