Search code examples
javascriptcountdown

Multiple countdown in same page


I need some help with javascript code, I try to get A code that will work for multi countdown timers at same page. I tried the code below but no success.

    <div class="expirydiv">Jan 02,2019</div>
    <div class="expirydiv">jun 15,2019</div>

    <script>
// Set the date we're counting down to

          var ps = document.querySelectorAll("div.expirydiv");

          var countDownDate = new Date(ps).getTime();

// Update the count down every 1 second

          var x = setInterval(function() {

// Get today's date and time

          var now = new Date().getTime();

// Find the distance between now and the count down date

          var distance = countDownDate - now;

// Time calculations for days, hours, minutes and seconds

          var days = Math.floor(distance / (1000 * 60 * 60 * 24));

          var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);



// Output the result in an element with classname="expirydiv"

    for(var i=0; i<ps.length; i++){
      ps[i].innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";

// If the count down is over, write some text

      if (distance < 0) {
        clearInterval(x);
        ps[i].innerHTML = "EXPIRED";
      }
      }
    }, 1000);

    </script>

The result of the code above appears like this:

    NaNd NaNh NaNm NaNs
    NaNd NaNh NaNm NaNs

What is wrong with this code, I think that the query selector fails to select the div.expirydiv as a date.


Solution

  • You are using multiple countdown so you need to iterate over them and set timer.

    var ps = document.querySelectorAll("div.expirydiv");
    ps.forEach(function(timer){
        var countDownDate = new Date(timer.innerText).getTime();
    
        var x = setInterval(function() {
    
            var now = new Date().getTime();
            var distance = countDownDate - now;
            var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    
            var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var seconds = Math.floor((distance % (1000 * 60)) / 1000);    
    
                timer.innerHTML = days + "d " + hours + "h "
                + minutes + "m " + seconds + "s ";
                if (distance < 0) {
                    clearInterval(x);
                    timer.innerHTML = "EXPIRED";
                  }
    
        }, 1000);    
    });
    <div class="expirydiv">Dec 02,2019</div>
    <div class="expirydiv">Dec 15,2019</div>