Skip to content Skip to sidebar Skip to footer

Separate Countdown For Divs

I want to show countdown in each of my divs. Right now I get the seconds from my database and store in in data-countdown attribute and then use the following js code for countdown.

Solution 1:

When you declare a variable without using the var keyword, you're creating a global. So each instance of your countdown is overwriting the previous value of finalDate, timeout, and time. Try adding var before each of those lines and it should do what you need. i.e.:

var finalDate = $(this).data('countdown');
var $this = $(this);
var timeout = null;
var time = null;
startCountdown($this,finalDate, 1000, end);

Solution 2:

You could also just do this in regular Javascript instead of jQuery...

var countdownDivs = document.querySelectorAll('div[data-countdown]');

functionend() {
    alert();
}
functioncountdown(display, timen, pause, callback) {
    display.innerHTML = timen;

    if (timen == 0) callback();
    else {
        display.timeout;
        clearTimeout(display.timeout);
        display.timeout = setTimeout(function () {
            countdown(display, timen - 1, pause, callback)
        }, pause);
    }
}

for(var i = countdownDivs.length>>>0; i--;){
    countdown(countdownDivs[i], countdownDivs[i].dataset.countdown, 1000, end);
}
div[data-countdown]{
    font-size:25px;
    color:#e3b40b;
    font-weight:600;
}
<divdata-countdown="12312312"></div><divdata-countdown="555555"></div><divdata-countdown="95695"></div>

Post a Comment for "Separate Countdown For Divs"