Home > database >  When countdown meet the end date i would like to replace a content but it going in minus
When countdown meet the end date i would like to replace a content but it going in minus

Time:01-22

When countdown meet the end date, I would like to replace a content but the count it's going negative.

  <script type="text/javascript">
    //define variables

    var second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;
    //get countdown
    var countDown = new Date('{{- end_date -}}').getTime(),
      x = setInterval(function () {
        var now = new Date().getTime(),
          distance = countDown - now;

        (document.querySelector('.js-timer-days').innerText = Math.floor(
          distance / day
        )),
          (document.querySelector('.js-timer-hours').innerText = Math.floor(
            (distance % day) / hour
          )),
          (document.querySelector('.js-timer-minutes').innerText = Math.floor(
            (distance % hour) / minute
          )),
          (document.querySelector('.js-timer-seconds').innerText = Math.floor(
            (distance % minute) / second
          ));
      }, second);
  </script>

enter image description here

I would like to replace a content when timer end.

CodePudding user response:

You can achieve this by adding an if statement after the code you have provided that checks to see if the distance is equal to 0. If it is, you can then replace the content with whatever you like.

if (distance <= 0) {
    clearInterval(x);
    document.querySelector('.js-timer-days').innerText = "Content to replace";
    document.querySelector('.js-timer-hours').innerText = "Content to replace";
    document.querySelector('.js-timer-minutes').innerText = "Content to replace";
    document.querySelector('.js-timer-seconds').innerText = "Content to replace";

}

CodePudding user response:

What do I have to add to this code?

You can use an if statement to check if the timer has finished, and then update the content accordingly. For example:

 var second = 1000,
    minute = second * 60,
    hour = minute * 60,
    day = hour * 24;
var countDown = new Date('{{- end_date -}}').getTime(),
    x = setInterval(function() {
            var now = new Date().getTime(),
                distance = countDown - now;
            document.querySelector('.js-timer-days').innerText = Math.floor(distance / (day)), document.querySelector('.js-timer-hours').innerText = Math.floor((distance % (day)) / (hour)), document.querySelector('.js-timer-minutes').innerText = Math.floor((distance % (hour)) / (minute)), document.querySelector('.js-timer-seconds').innerText = Math.floor((distance % (minute)) / second);
            if (distance <= 0) { //Timer has finished document.querySelector('.js-timer-days').innerText = 'Timer finished'; 
                //Update content here } }, second)
                }
  • Related