Simple jQuery countdown

in code


It counts down to a certain moment in time. Thanks to Alanna for explaining principles related to hardware timekeeping. :)

// Target date. See:
// http://www.w3schools.com/jsref/jsref_obj_date.asp
var target = new Date(2014,06,18,5,30,0,0);

if ($.now() > target.getTime()) {
    target.setFullYear(target.getFullYear() + 1);
}

var countdown = {
    days : 0,
    hours : 0,
    minutes : 0,
    seconds : 0
}

var divs = [
    '#countdown-days',
    '#countdown-hours',
    '#countdown-minutes',
    '#countdown-seconds'
];

function updateCountdown() {
    // Countdown needs to be recalculated each tick. 
    // Simple decrement is too error-prone otherwise.
    var now = new Date($.now());

    countdown.days    = Math.floor((target.getTime() - now.getTime()) / 86400000);
    countdown.hours   = 24 - (24 - target.getHours()) - now.getHours() - 1;
    countdown.minutes = 60 - target.getMinutes() - now.getMinutes() - 1;
    countdown.seconds = 60 - target.getSeconds() - now.getSeconds() - 1;

    // If the current time past the hour is greater than the target time past the hour.
    // -or hour of the day is greater than target hour of the day-then the counter will
    // be negative. This corrects it.
    countdown.hours = (countdown.hours < 0 ) ? 24 + countdown.hours : countdown.hours;
    countdown.minutes = (countdown.minutes < 0) ? 60 + countdown.minutes : countdown.minutes;
}

function drawCountdown() {
    var n = 0;
    $.each(countdown, function(key, value) {
        value = (value < 0) ? 0 : value;
        $(divs[n]).text(value);
        n++;
    });
}

function centerCooldown() {
    var a = $(window).height() * 0.5;
    var b = $('.content').height() * 0.5;
    $('.content').css('padding-top', a - b + 'px');
}

$(function() {
    centerCooldown();
    updateCountdown();
    drawCountdown();
});

setInterval(function() {
    updateCountdown();
    drawCountdown();
}, 1000);


March 20

in me


Your email address will not be published. Required fields are marked *