Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple countdown on single page

Below are the html code for countdown. I am using jquery.countdown.min.js plugin.

<ul id="example">
<li><span class="days">00</span><p class="days_text">Days</p></li>
        <li class="seperator">:</li>
        <li><span class="hours">00</span><p class="hours_text">Hours</p></li>
        <li class="seperator">:</li>
    <li><span class="minutes">00</span><p class="minutes_text">Minutes</p></li>
        <li class="seperator">:</li>
    <li><span class="seconds">00</span><p class="seconds_text">Seconds</p></li>
    </ul>

    <div id= "count" data-text="01/01/2016 05:06:59"></div>

and here are the javascript code.

<script type="text/javascript">
    var val1 = $('#count').data('text');

        $('#example').countdown({
            date: val1,
            offset: 0,
            day: 'Day',
            days: 'Days'
        }, function () {
            alert('Done!');
        });
    </script>

It is working fine and giving me the desired output. The limitation is i can use only one countdown timer per page. If i want to use multiple on same page then i have to add multiple javascript code.

Below is the scenario.

<ul id="example">
        <div data-countdown="01/01/2016 05:06:59"></div>
         <div data-countdown="01/01/2017"></div>
         <div data-countdown="01/01/2018"></div>
        <div data-countdown="01/01/2020"></div>   
      </ul>

I tried below code but it is not working.

<script type="text/javascript">
     $('[data-countdown]').each(function() {
   var $this = $(this),finalDate = $(this).data('countdown');
        $this.countdown({
            date: finalDate,
            offset: 0,
            day: 'Day',
            days: 'Days'
        }, function () {
            alert('Done!');

        });
        });
    </script>
like image 294
Roxx Avatar asked Jun 07 '15 04:06

Roxx


2 Answers

Update:

JSFiddle

    <div id="example1" data-countdown="01/01/2016 05:06:59"></div>
    <div id="example2" data-countdown="01/01/2017"></div>
    <div id="example3" data-countdown="01/01/2018"></div>
    <div id="example4" data-countdown="01/01/2020"></div>   

$(function(){
   $('[data-countdown]').each(function() {
      var $this = $(this), finalDate = $(this).data('countdown');
      $this.countdown(finalDate, function(event) {
         $this.html(event.strftime('%D days %H:%M:%S'))}).on('finish.countdown', function() {
            alert("Finish"); 
          });
     });
 });
like image 148
Siamak Ferdos Avatar answered Sep 20 '22 10:09

Siamak Ferdos


Javascript and html are friends. When you found something strange happened in the js code, validate the html first. In your case, if you stick on the "ul", use "ul—li—div" structure; otherwise use "div—div" or "nav—div" or "section—div" if applicable

like image 26
XuChu LIU Avatar answered Sep 18 '22 10:09

XuChu LIU