jQuery. How do I select live created element? - javascript

Here is the code:
helpers.ajaxModuleFormRequest('blockcallback', $(this), function() {
var timer = $('[data-timer]');
var seconds = timer.data('timer');
var interval = setInterval(function() {
if (seconds == 0) {
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
});
helper.ajaxModuleFormRequest() does an AJAX-request and then in $.ajax.done() method calls callback-function specified in 3rd param.
<div data-timer="20"></div> is inserted in DOM live $.ajax.done() method and I want to select it to start the timer. But the code doesn't work, $('[data-timer]').length returns 0. How can I fix this?

Here's a simplified example, which inserts a <div> dynamically and then starts the timer:
Html:
<html>
<head>Testpage</head>
<body></body>
</html>
JavaScript:
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
Note that initially the <div> is not there, it is inserted dynamically via
$('body').append('<div data-timer="20"></div>');
If you want to test whether it tests correctly for existance of the timer value, comment the line above, i.e.
// $('body').append('<div data-timer="20"></div>');
and you'll get the alert message "Please specify a timer value!".
Try it on jsfiddle:
jsfiddle
{
$('body').append('<div data-timer="20"></div>');
var timer = $('[data-timer]');
var seconds = timer.data('timer');
if (seconds!==undefined)
{
alert(seconds);
var interval = setInterval(function() {
if (seconds == 0) {
alert('elapsed!');
clearInterval(interval);
}
timer.text(seconds);
seconds--;
}, 1000);
}
else
{
alert("Please specify a timer value!");
}
}
<head>Testpage</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

issue with if else conditional

When the page is open, it automatically set's a timeout to preform a task.
What i want is to change the timing if an event occur. If the user click a button, it changes the time right after the click.
If the user does nothing, the page should auto refresh after a given time, if the user click on "#b1" , the initial timeout should be interrupted and beggin a new one with other time set
I've tried the previous code, but it only executes the last alert .
How can i accomplish this ?
var clicked = 0;
var time = '';
$('#b1').click(function() {
clicked = 1;
});
if (clicked == 1) {
time = 10;
setTimeout(function() {
alert('clicked');
}, time);
} else {
time = 10000;
setTimeout(function() {
alert('nothingDone');
}, time);
}
Define a global variable where setTimeout is the value, call clearTimeout() with variable as parameter if user clicks #b1 element, then set variable to setTimeout() call within event handler
$(function() {
var clicked = 0;
var time = '';
var timer;
function updateTimer() {
time = 10;
timer = setTimeout(function() {
alert('clicked');
}, time);
}
$('#b1').click(function() {
clicked = 1;
clearTimeout(timer);
updateTimer()
});
if (clicked == 1) {
updateTimer()
} else {
time = 10000;
timer = setTimeout(function() {
alert('nothingDone');
}, time);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="b1">click</div>

JQuery count up with a timeout or endpoint

I have a timer which counts up to a figure based on a set of results from the database. however, when the data isnt present the timer will just keep going with no timeout or end point.
Is there a way I can either not show the timer if the value does not exist or show 0/40 see my code below:
$(function() {
function count($this) {
var current = parseInt($this.html(), 10);
$this.html(++current);
if (current !== $this.data('count')) {
setTimeout(function(){
count($this)
}, 50);
}
}
$(".fiveStarScore").each(function() {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
});
This is the div that is targeted and will stop at the desired value.
<div>
<span class="fiveStarScore"><?php echo $total_five_stars;?></span>/40
</div>
You can fix this by checking if the text value of the element on load is 0 (or is any non numerical value) and not calling count() if so:
$(function() {
function count($el) {
var current = parseInt($el.text(), 10);
$el.html(++current);
if (current !== $el.data('count')) {
setTimeout(function() {
count($el)
}, 50);
}
}
$(".fiveStarScore").each(function() {
var $el = $(this);
var total = parseInt($el.text(), 10) || 0;
$el.data('count', total).text('0');
if (total == 0)
return;
count($el);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span class="fiveStarScore">0</span>/40
</div>
<div>
<span class="fiveStarScore">25</span>/40
</div>

Javascript countdown timer to change image and link

Apologies in advance for being somewhat out of my depth here.
I am trying to use a JavaScript countdown timer on an ASP page to do the following - every sixty seconds after the a page loads, an image-based link will switch between one of five image/link combinations.
I've done something somewhat wrong here, and I can't find the problem. It never runs.
Thanks in advance for any assistance.
The images are named the following:
1_AdvoImg.gif 2_AdvoImg.gif 3_AdvoImg.gif 4_AdvoImg.gif 5_AdvoImg.gif
The urls are the following:
linkone.html linktwo.html linkthree.html linkfour.html linkfive.html
The html encapsulating the link is this:
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
The javascript is this:
<script language="javascript">
function startTimer(duration) {
var timer = duration, seconds, imgprefix, imgname, linkurl;
imgprefix = 1;
setInterval(function () {
seconds = parseInt(timer % 60, 10);
imgname = imgprefix.concat("_AdvoImg.gif");
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
if (--timer <= 0) {
document.getElementById("AdvoLink").href = "";
document.getElementById("AdvoImg").src = imgname;
++imgprefix;
timer = duration;
}
}, 5);
}
window.onload = function () {
startTimer(60);
};
</script>
You are trying to build a timer inside a timer there.
Try keeping it as simple as possible.
What you actually need is just:
window.onload = function () {
setInterval(function () {
//your url changing magic here - without the timer stuff
}, 60000);
};
With this, your magic code should trigger every 60000 milliseconds => 60s => 1minute.
You could actually kinda "debug" it by using console.log() inside your loop.
dunno what you were using var seconds for so I removed it
edited to stop image number going over 5, change if loop to whatever number you need
function startTimer(duration) {
var timer = duration;var seconds;var imgprefix;var imgname;var linkurl;
imgprefix = 1;
setInterval(function() {
imgname = imgprefix+"_AdvoImg.gif";
if (imgprefix == 1) {
linkurl = "linkone.html";
}
if (imgprefix == 2) {
linkurl = "linktwo.html";
}
if (imgprefix == 3) {
linkurl = "linkthree.html";
}
if (imgprefix == 4) {
linkurl = "linkfour.html";
}
if (imgprefix == 5) {
linkurl = "linkfive.html";
}
document.getElementById("timer").innerHTML=timer;
timer--;
if (timer <= 0) {
document.getElementById("AdvoLink").href = linkurl;
document.getElementById("AdvoImg").src = imgname;
document.getElementById("result").innerHTML = "image src = "+imgname+" and href = "+linkurl;
if(imgprefix < 5){++imgprefix;}else{imgprefix =1;}
timer = duration;
}
}, 200//speed up and slow down here, in milliseconds
);
}
window.onload = function () {
startTimer(10);
};
<a id='AdvoLink' href='../'><img id='AdvoImg' src='' border="0"></a>
<div id="timer"> </div>
<div id='result'> </div>

Pause / Resume jQuery Countdown Timer

I'm trying to make a countdown timer that can be paused with a single HTML5 button tag using a JS onClick() event, or more preferably, using jQuery with something like $("#pause_resume").off('click').on('click', firstClick)in conjunction with another function. Logically, I would assume the task would require getting the current values of both $.min and $.sec and then setting these values, while switching functions, until the "resume" button is pressed again. But I honestly have no idea how to go about doing this. I've looked at other code on this site and others, but what I saw was heavily deprecated and not in line with my project plan. Any insight is appreciated.
HTML:
<p class="timer">
<span class="min"></span>:<span class="sec"></span>/
<span class="fullTime">1:30</span>
</p>
JavaScript:
<script type="text/javascript">
var timer = $('.timer');
var leadingZero = function(n) {
if (n < 10 && n >= 0)
return '0' + n;
else
return n;
};
var minutes = 1;
var seconds = 30;
setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds == 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
</script>
Well, I think this is what you want. http://jsfiddle.net/joey6978/67sR2/3/
I added a button that toggles a boolean on click to determine whether to set your function in the interval or to clear the interval.
var clicked=true;
var counter;
$('button').click(function(){
if(clicked){
counter=setInterval(function () {
var m = $('.min', timer),
s = $('.sec', timer);
if (seconds === 0) {
minutes--;
seconds = 59;
} else {
seconds--;
}
m.text(minutes);
s.text(leadingZero(seconds));
}, 1000);
}
else{
clearInterval(counter);
}
clicked=!clicked;
});

How do I display a div when my timer hits zero?

here's my code:
$('#TESTER').hide();
$('#titlehead2').click(
function() {
var doUpdate = function() {
$('.countdown').each(function() {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
}
});
};
setInterval(doUpdate,1000);
if(count <= 0) $('#TESTER').show();
}
);
#TESTER is the div I want to display when the timer reaches zero, and #titlehead2 is my play button for the timer. Any help will be much appreciated.
You need to check the value of counter within the timer
$('#TESTER').hide();
$('#titlehead2').click(function () {
var doUpdate = function () {
//need to look whether the looping is needed, if there are more than 1 countdown element then the timer logic need to be revisted
$('.countdown').each(function () {
var count = parseInt($(this).html());
if (count !== 0) {
$(this).html(count - 1);
} else {
$('#TESTER').show();
//you also may want to stop the timer once it reaches 0
clearInterval(timer);
}
});
};
var timer = setInterval(doUpdate, 1000);
});

Categories