Search code examples
javascriptjquerycountdowninstances

jQuery countdown plugin multiple instances not working


i have problem with my script using jquery.countdown.js plugin, it doesn't sets multiple instances for each element i pass it to, it always sets the first instance for all, so countdowns are always the same.

link to plugin : http://keith-wood.name/countdown.html

   $(function(){

     $.each($('.countdown'), function() {
     var _element = '.countdown-'+$(this).attr("id");
     if($(_element).length > 0){
    var _expDate = $(_element).attr('data-expiration').split(',');
    var _datetime = Date(_expDate);
    init_countdown(_element,_datetime);
   }

});      
});

  function init_countdown(_element,_datetime){
    console.log(_element + ", " + _datetime)
    $(_element).countdown({
      until: _datetime,
      format: 'yowdHMS'
    });

  }

HTML:

<h5 class="muted countdown countdown-1" id="1" data-expiration="2014,10,26,14,10,35"> 2014-10-26 14:10:35</h5>
<h5 class="muted countdown countdown-2" id="2" data-expiration="2014,10,26,16,10,35"> 2014-10-26 16:10:35</h5>
<h5 class="muted countdown countdown-3" id="3" data-expiration="2014,10,26,18,10,35"> 2014-10-26 18:10:35</h5>

this is how it outputs

enter image description here

how can i fix this?

console.log() 

.countdown-1, Sun Oct 28 2012 22:10:09 GMT+0100 (CET)


.countdown-2, Sun Oct 28 2012 22:10:09 GMT+0100 (CET)


.countdown-3, Sun Oct 28 2012 22:10:09 GMT+0100 (CET)

@Asad example:

enter image description here


Solution

  • The date constructor (in the form you are using it) accepts several integer values, not an array. You need to turn each value in the array that results from your split into a integer (using parseInt), then pass each argument individually, and not as an array.

    Try this:

    var _expDate = $(_element).attr('data-expiration').split(',');
    _expDate.forEach(function(v,i,a){a[i]=parseInt(a[i]);});
    var _datetime = new Date(_expDate[0],_expDate[1],_expDate[2],_expDate[3],_expDate[4],_expDate[5]);