jQuery Countdown

A jQuery plugin that sets a div to show a countdown to a given time. If you find this plugin useful please vote for it on the jQuery site.

Download all the files in one go - available under the GPL and MIT licences. The current version is 1.3.0. For more detail see the documentation reference page.

Default Settings

The countdown functionality can easily be added to a division with appropriate default settings, although you do need to set the target time. You can just as easily remove the countdown widget if it is no longer required.

Default countdown:

 
$('#defaultCountdown').countdown({until: liftoffTime});

$('#removeCountdown').toggle(function() {
                $(this).text('Re-attach');
                $('#defaultCountdown').countdown('destroy');
        },
        function() {
                $(this).text('Remove');
                $('#defaultCountdown').countdown({until: liftoffTime});
        }
);

The defaults are:

Text is in English Format is 'dHMS' Days are shown if needed Hours/minutes/seconds are shown

You can override the defaults globally as shown below:

$.countdown.setDefaults({description: 'Until liftoff'});

Processed fields are marked with a class of hasCountdown and are not re-processed if targetted a second time.

Basic Formats

You can control how the countdown is presented via the format setting. This is one or more of the following characters: 'Y' for years, 'O' for months, 'W' for weeks, 'D' for days, 'H' for hours, 'M' for minutes, 'S' for seconds. Use upper-case characters for required fields and the corresponding lower-case characters for display only if non-zero.

Don't show days:

$('#noDays').countdown({until: liftoffTime, format: 'HMS'});

Don't show seconds:

$('#noSeconds').countdown({until: liftoffTime, format: 'dHM'});

Don't show either:

$('#noDaysSeconds').countdown({until: liftoffTime, format: 'HM'});

Compact version:

$('#compact').countdown({until: liftoffTime, compact: true,
        description: ''});

Minimal compact version:

$('#minimal').countdown({until: liftoffTime, compact: true,
        format: 'HM', description: ''});

Formatted description:

$('#formatted').countdown({until: liftoffTime, 
        description: 'To the <i>next release</i> of <a href="' +
        'http://jquery.com/plugins/project/countdown2">jQuery Countdown</a>!'});

Extended Formats

For targets further in the future, there are more presentation options.

Show it all:

$('#showAll').countdown({until: longWayOff, format: 'YOWDHMS'});

By month:

$('#byMonth').countdown({until: longWayOff, format: 'odHM'});

By week:

$('#byWeek').countdown({until: longWayOff, format: 'wdHM'});

Strange combination:

$('#strangeCombo').countdown({until: longWayOff, format: 'WHS'});

Compact version:

$('#compactAll').countdown({until: longWayOff, compact: true,
        format: 'YOWDHMS', description: ''});

Show all values as needed:

$('#asNeeded').countdown({until: liftoffTime, format: 'yowdHMS'});

Show all values always:

$('#alwaysShow').countdown({until: liftoffTime, format: 'YOWDHMS'});

Count Up Since a Time

You can count up from a previous date/time, instead of down to a future date/time. Note that there will be no expiry event in this case.

Count up:

 

$('#sinceCountdown').countdown({since: startYear,
        format: 'YOWDHMS', description: 'Since New Year'});
$('#sinceCompact').countdown({since: startYear, compact: true,
        format: 'YOWDHMS', description: ''});

Relative Base Times

You can set the until and since values relative to the current time, instead of as an absolute value. A number on its own is treated as seconds. Otherwise use a string to specify the number and units: 'Y' for years, 'O' for months, 'W' for weeks, 'D' for days, 'H' for hours, 'M' for minutes, 'S' for seconds. Either upper or lower case letters may be used. Multiple offsets may be combined into one setting.

Until 300 seconds time:

$('#until300s').countdown({until: +300});

Until two days time:

$('#until2d').countdown({until: '+2d'});

Since three weeks ago:

$('#since3w').countdown({since: '-3W', description: 'Since last time'});

Until two days and four hours time:

$('#until2d4h').countdown({until: '+2d +4h'});

Pause/Resume and Lap Times

You can pause and later resume a countdown from where you left off.

Pause/resume:

 

 

$('#pauseResume').countdown({until: liftoffTime, onTick: showPauseTime});

$('#pauseButton').toggle(function() {
                $(this).text('Resume');
                $('#pauseResume').countdown('pause');
        },
        function() {
                $(this).text('Pause');
                $('#pauseResume').countdown('resume');
        }
);

function showPauseTime(periods) {
        $('#showPauseTime').text(periods[4] + ':' + twoDigits(periods[5]) +
                ':' + twoDigits(periods[6]));
}

Or you can pause to display a lap time while the countdown continues.

Lap time:

 

 

$('#lapTime').countdown({until: liftoffTime, onTick: showLapTime});

$('#lapButton').toggle(function() {
                $(this).text('Resume');
                $('#lapTime').countdown('lap');
        },
        function() {
                $(this).text('Pause');
                $('#lapTime').countdown('resume');
        }
);

function showLapTime(periods) {
        $('#showLapTime').text(periods[4] + ':' + twoDigits(periods[5]) +
                ':' + twoDigits(periods[6]));
}

Time Zones

Cater for time zones with the serverTime setting. Set this in the page based on the time at the originating server and the local time is offset accordingly.

Server is one hour ahead:

var server1 = new Date();
server1.setHours(server1.getHours() + 1);
$('#server1').countdown({until: liftoffTime, serverTime: server1});

Server is two hours behind:

var server2 = new Date();
server2.setHours(server2.getHours() - 2);
$('#server2').countdown({until: liftoffTime, serverTime: server2});

Server on GMT:

var serverGMT = new Date();
serverGMT.setMinutes(serverGMT.getMinutes() + serverGMT.getTimezoneOffset());
$('#serverGMT').countdown({until: liftoffTime, serverTime: serverGMT});

Callback Events

On expiry a callback is made to allow you to action the countdown. You can force this event to fire even if the countdown starts after the target time by setting alwaysExpire to true.

You can also monitor the countdown on each tick of the clock.

Action it in 5 seconds:

 

 

$('#shortlyStart').click(function() {
        shortly = new Date();
        shortly.setSeconds(shortly.getSeconds() + 5.5);
        $('#shortly').countdown('change', {until: shortly});
});

$('#shortly').countdown({until: shortly, 
        onExpiry: liftOff, onTick: watchCountdown});

function liftOff() {
        alert('We have lift off!');
}

function watchCountdown(periods) {
        $('#monitor').text('Just ' + periods[5] + ' minutes and ' +
                periods[6] + ' seconds to go');
}

Or do it your own way on the tick callback and hide the countdown div.

Time to go:

$('#hidden').countdown({until: liftoffTime, format: 'HMS', onTick: ownWay});

function ownWay(periods) {
        $('#ownWay').text(periods[4] + ':' + twoDigits(periods[5]) +
                ':' + twoDigits(periods[6]));
}

You can have a new page loaded automatically on expiry. Use the Back button to return.

Load new page:

 
$('#newPageStart').click(function() {
        shortly = new Date();
        shortly.setSeconds(shortly.getSeconds() + 5.5);
        $('#newPage').countdown('change', {until: shortly});
});

$('#newPage').countdown({until: shortly, expiryUrl: 'http://jquery.com',
        description: 'To go to jQuery'});

Localisation

You can localise the countdown for other languages and regional differences.

:

 

$('#l10nCountdown').countdown({until: longWayOff,
        format: 'YOWDHMS', description: 'Jusqu\'Ã  le lancement'});
$('#l10nCompact').countdown({until: longWayOff, compact: true,
        format: 'YOWDHMS', description: ''});

You need to load the appropriate language package (see list below), which adds a language set ($.countdown.regional[langCode]) and automatically sets this language as the default for all countdown divs.

<script type="text/javascript" src="jquery.countdown-fr.js"></script>

Thereafter, if desired, you can restore the original language settings.

$.countdown.setDefaults($.countdown.regional['']);

And then configure the language per countdown.

$('#l10n').countdown($.countdown.regional['fr']);

Miscellaneous

Add curvy corners to your countdown. You need to wrap the countdown division in another division to which the curvy corners are applied.

Curvy-corners:

$('#curvyWrapper').corner();
$('#curvyCorners').countdown({until: liftoffTime});

Retrieve the current periods from a countdown timer.

Current periods:

 

$('#getNow').click(function() {
        var periods = $('#curvyCorners').countdown('getTimes');
        var text = '';
        for (var i = 0; i < periods.length; i++) {
                text += periods[i] + ' ' + $.countdown.regional[''].labels[i] + ' ';
        }
        $('#curPeriods').text(text);
});

Version Compatibility

Several interface changes were made between v1.0 and v1.1 to bring the plugin into line with the new UI interface standards.

To assist in the upgrade process, a compatibility module is available that allows a v1.0 page to be run against the latest code.

Just add the following line to your page after the plugin load to continue running:

<script type="text/javascript" src="jquery.countdown.compat-1.0.js"></script>

To complete the upgrade perform the following steps:

Replace $(…).attachCountdown(…) with $(…).countdown(…) Replace $(…).changeCountdown(…) with $(…).countdown('change', …) Replace $(…).removeCountdown() with $(…).countdown('destroy') Replace showDays setting with a value in the format setting: 'D' for 'always', 'd' for 'asNeeded', or '' for 'never' Replace showSeconds setting with a value in the format setting: 'S' for true or '' for false

Quick Reference

A full list of all possible settings is shown below. Note that not all would apply in all cases. For more detail see the documentation reference page.

$('selector').countdown({
        until: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count down to
                // or numeric for seconds offset, or string for unit offset(s):
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
        since: null, // new Date(year, mth - 1, day, hr, min, sec) - date/time to count up to
                // or numeric for seconds offset, or string for unit offset(s):
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
        format: 'dHMS', // Format for display - upper case for always, lower case only if non-zero,
                // 'Y' years, 'O' months, 'W' weeks, 'D' days, 'H' hours, 'M' minutes, 'S' seconds
        compact: false, // True to display in a compact format, false for an expanded one
        description: '', // The description displayed for the countdown
        labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
                // The expanded texts for the counters
        labelsSingle: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
                // The expanded texts for the counters if only one
        compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
        compactLabelsSingle: ['y', 'm', 'w', 'd'], // The compact texts for the counters if only one
        timeSeparator: ':', // Separator for time periods
        expiryUrl: null, // A URL to load upon expiry, replacing the current page
        alwaysExpire: false, // True to trigger onExpiry even if never counted down
        onExpiry: null, // Callback when the countdown expires -
                // receives no parameters and 'this' is the containing division
        onTick: null, // Callback when the countdown is updated -
                // receives int[7] being the breakdown by period (based on format)
                // and 'this' is the containing division
        serverTime: null // The current time on the server,
                // to calculate an offset for other time zones
});

Usage

Include the jQuery library in the head section of your page.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>

Download and include the jQuery Countdown CSS and the jQuery Countdown Javascript in the head section of your page.
<style type="text/css">@import "jquery.countdown.css";</style>
<script type="text/javascript" src="jquery.countdown.js"></script>

Alternately, you can use the packed version jquery.countdown.pack.js (6.0K vs 16.3K), or the minified versions jquery.countdown.min.css (0.6K vs 0.5K, 0.2K when gzipped) and jquery.countdown.min.js (7.1K, 2.6K when gzipped). Connect the countdown functionality to your divs.
$('div selector').countdown({until: liftoffTime});

You can include custom settings as part of this process.
$('div selector').countdown({until: liftoffTime, format: 'dHM'});

For more detail see the documentation reference page.

Localisations

Localisation packages are available for download and should be loaded after the main time entry code. These packages automatically apply their settings as global default values.

Chinese - Simplified (简体中文) - jquery.countdown-zh-CN.js (thanks to Cloudream) Chinese - Traditional (ç¹é«”中文) - jquery.countdown-zh-TW.js (thanks to Cloudream) Czech (Čeština) - jquery.countdown-cs.js (thanks to Miroslav Koula) Dutch (Nederlands) - jquery.countdown-nl.js (thanks to Mathias Bynens) French (Français) - jquery.countdown-fr.js German (Deutsch) - jquery.countdown-de.js Hungarian (Magyar) - jquery.countdown-hu.js (thanks to Edmond L.) Italian (Italiano) - jquery.countdown-it.js (thanks to Davide Bellettini) Polish (Polski) - jquery.countdown-pl.js (thanks to Pawel Lewtak) Portuguese - Brazilian (Português) - jquery.countdown-pt-BR.js (thanks to Marcelo Pellicano de Oliveira) Romanian (Română) - jquery.countdown-ro.js (thanks to Edmond L.) Spanish (Español) - jquery.countdown-es.js (thanks to Sergio Carracedo Martinez) Turkish (Türkçe) - jquery.countdown-tr.js (thanks to Bekir AhmetoÄŸlu)

Other translations welcomed.

Comments

It's awesome! You saved me a lot of time trying to create something that does the equivalent...
Daniel McGhan

Thanks for the great work on JQuery Countdown.
Alvin Singh

Your jQuery Countdown script is awesome.
Burak Erdem

Estou usando seu script, muito bom, jQuery Countdown.
Tulio Galli

Contact Keith Wood at kbwood@virginbroadband.com.au with comments or suggestions.

Change History

Version Date Changes
1.3.0 5 July 2008
Internal changes for instance values Added 'getTimes' command to retrieve array of current periods Added 'pause', 'lap', and 'resume' commands to allow pausing and resuming of countdowns
1.2.2 14 June 2008
Bug fix for compact times with hours/minutes/seconds
1.2.1 7 June 2008
Added relative values for until and since Added serverTime option to allow for time zone differences Added alwaysExpire option to force the onExpiry event if starting after the target time Added labelsSingle and compactLabelsSingle options for labels applying to a singular period Added Polish localisation
1.2.0 3 May 2008
Added since option for counting up Added Czech, Dutch, Hungarian, Portuguese (Brazilian), Romanian, Spanish localisations
1.1.1 23 Feb 2008
Corrected bugs in period calculations for years/months Changed 'remove' command to 'destroy'
1.1.0 16 Feb 2008
Updated interface to conform to jQuery UI standards Replaced showDays and showSeconds with format setting Added expiryUrl setting Added Simplified Chinese, Traditional Chinese, Italian localisations Added backwards compatibility module for v1.0
1.0.0 26 Jan 2008
Initial release


You are viewing a mobilized version of this site...
View original page here

Mobilized by Mowser Mowser