jquery - How to run multiple countdowns with single javascript function? -


i have multiple countdowns on page on page load. want make work single javascript function. have tried many ways make work of them worked me.

i have found similar questions here none of them helped me.

what doing wrong? should do?

http://jsfiddle.net/d3g840pe/1/

html:

<table>     <tr id="id1">         <td>img</td>         <td>#</td>         <td>type</td>         <td>status</td>         <td>             <span class="counter" rel='120'></span>         </td>     </tr>     <tr id="id2">         <td>img</td>         <td>#</td>         <td>type</td>         <td>status</td>         <td>             <span class="counter" rel='200'></span>         </td>     </tr>     <tr id="id3">         <td>img</td>         <td>#</td>         <td>type</td>         <td>status</td>         <td>             <span class="counter" rel='50'></span>         </td>     </tr> </table> 

js:

$(function() {     $tr = $('.counter').closest('tr');     $trid = $tr.attr('id');     $span = $('#' + $trid).find('.counter');     $counter = $span.attr('rel');     setinterval(function() {         $counter--;         $span.attr('rel', $counter);         if ($counter >= 0) {             $span.html($counter);         }         // display '$counter' wherever want display it.         if ($counter === 0) {             //return true;             console.log('finished');             clearinterval($counter);         }     }, 1000); }); 

iterate on each element .counter class , run setinterval timer.

$(function () {     $('.counter').each(function () {         var duration = +$(this).attr('rel'), // <--- + same parseint()             $span = $(this);         var counter = setinterval(function () {             duration--;             $span.attr('rel', duration);             $span.html(duration);             if (duration <= 0) {                 console.log('finished');                 clearinterval(counter);             }         }, 1000);     }); }); 

here demo http://jsfiddle.net/d3g840pe/2/

also, not quite sure why used rel attribute. instead of use data-* attribute

<span class="counter" data-duration=200> 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -