Search code examples
javascriptjquerycountdown

Problems with (multiple) jQuery count up


I'm working on a countup right now. The goal is to display multiple countups on a page. One countup with an interval() is not a problem, but when it gets to two or more countups it will only display the last countup.

Countup structure:

  • Grab the unix timestamp from <div value"....."> <div>

    Example: <div id=countup value"jan,01,2015, 00:00:00"> <div>

  • Turn unix timestamp with jQuery to a nice countdown.

  • Display all countups on the page with .html() or .text()

Jsfiddle.net

Hope you can help me out.


Solution

  • Is something like this what you're looking for?:

    <div class="countup" value="jan,01,2014,00:00:00"></div>
    <div class="countup" value="feb,05,2015,13:00:00"></div>
    
    function upTime(element) {
        now = new Date();
        countTo = new Date(element.getAttribute("value"));
        difference = (now-countTo);
    
        days=Math.floor(difference/(60*60*1000*24)*1);
        hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1);
        mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
        secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
    
        element.innerHTML =  "It's been " + days + " days " + hours + " hours " + mins + " minutes " + secs + " seconds";
    
        setTimeout(function(){ upTime(element); },1000);
    }
    
    var elements = document.getElementsByClassName("countup");
    for (var i = 0; i < elements.length; i += 1) {
        upTime(elements[i]);
    }
    

    jsFiddle: http://jsfiddle.net/6f6c8z4a/1/

    Output:

    It's been 405 days 13 hours 58 minutes 43 seconds
    It's been 5 days 0 hours 58 minutes 43 seconds
    

    One thing to note is that setTimeout(.., 1000) is not a reliable way to run code every second because setTimeout makes a best effort. In practice the timer will start to skew pretty quickly. You can consider running this code more often (every 100ms) or you can ignore the skew.