try to re-initialize $('#hideMsg span')
. like $('#hideMsg span').text('5');
Issue with jQuery countdown timer
-
07-10-2022 - |
Question
I'm working with timers when I click the button timer starts from 5 seconds and fadesout when it comes to 0. I tried but couldnt get , here is the fiddle I've tried: http://jsfiddle.net/GNrUM/937/
<div id="hideMsg" style="display:none;">
This Box will Close In <span>5</span> Seconds..</div>
<input id="take" type="button" value="click me" >
jQuery code :
$("#take").live("click", function () {
$('#hideMsg').show();
var sec = $('#hideMsg span').text()
var timer = setInterval(function () {
$('#hideMsg span').text(--sec);
if (sec == 0) {
$('#hideMsg').fadeOut('fast');
clearInterval(timer);
}
}, 1000);
});
It's working good for first click, when click 2 time count starts from 0,-1,-2,. It does not clear the intervals. any help?
Solution
OTHER TIPS
Try this:
$("#take").live("click",function(){
$('#hideMsg').show();
var sec = $('#hideMsg span').text()
var timer = setInterval(function() {
$('#hideMsg span').text(--sec);
if (sec == 0) {
$('#hideMsg').fadeOut('fast');
$('#hideMsg span').text("5"); // reinitialize the span value
clearInterval(timer);
}
}, 1000);
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow