javascript - multiple countdowns on same page with jquery -
i'm having little problem jquery/javascript countdown , i'm hoping can me.
so, have timer function, has 1 parameter, called selector (jquery selector) ..
function timer(selector) { self = $(selector); var sec = parseint(self.find('span.timeout').text()); var interval = setinterval(function() { sec--; if (sec >= 0) { self.find('span.timeout').text(sec); } else { setinterval(interval); } }, 1000); } in, html have this.
<div class="element" id="el1"><span class="timeout">10</span></div> <div class="element" id="el2"><span class="timeout">10</span></div> multiple elements same class , different id's
and usage of function this:
$("body").on('click', '.element', function() { timer(this); }); on first click works fine, timer counts down. when click on second div same class, first counter stops , second goes previous second.
so, how can multiple countdowns on same page js/jquery, click on both elements , both timers work fine?
- you forgot declare
selfvar. result,selfbecame global variable. overwriting global ("shared") variable when second timer being created. so, both timers on, @ same time, ouputting second element, causing glitches. - you meant
clearinterval(interval).
Comments
Post a Comment