A jQueryplugin
that sets a div or span to show a countdown to a given time.
The current version is 2.1.0 and is available
under the MIT licence.
For more detail see the documentation reference page.
Or see a minimal page that you could
use as a basis for your own investigations.
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 also remove the countdown widget if it is no longer required.
Default countdown:
var newYear = new Date();
newYear = new Date(newYear.getFullYear() + 1, 1 - 1, 1);
$('#defaultCountdown').countdown({until: newYear});
$('#removeCountdown').click(function() {
var destroy = $(this).text() === 'Remove';
$(this).text(destroy ? 'Re-attach' : 'Remove');
$('#defaultCountdown').countdown(destroy ? 'destroy' : {until: newYear});
});
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:
Processed fields are marked with a class of hasCountdown
and are not re-processed if targetted a second time.
A note on Date - the JavaScript Date constructor expects
the year, month, and day as parameters. However, the month ranges from 0 to 11.
To make explicit what date is intended (does a month of 3 mean March or April?)
I specify the month from 1 to 12 and manually subtract the 1.
Thus the following denotes 25 December, 2014.
$(selector).countdown({since: new Date(2014, 12-1, 25)});
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.
Create your own customised layout for more control over the countdown appearance.
Indicate substitution points with '{desc}' for the description,
'{sep}' for the time separator, '{pv}' where
p is 'y' for years, 'o' for months, 'w' for weeks, 'd' for days,
'h' for hours, 'm' for minutes, or 's' for seconds and v is
'n' for the period value, 'nn' for the period value with a
minimum of two digits, 'nnn' for the period value with a
minimum of three digits, or 'l' for the period label
(long or short form depending on the compact setting),
or '{pd}' where p is as above and d is '1' for the units digit,
'10' for the tens digit, '100' for the hundreds digit,
or '1000' for the thousands digit.
If you need to exclude entire sections when the period value is zero
and you have specified the period as optional, surround these sections
with '{p<}' and '{p>}', where p is the same as above.
Your layout can just be simple text, or can contain HTML markup as well.
You can even embed your HTML within the countdown division/span
and reference it from there.
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.
Cater for time zones with the timezone setting, which is set
to the target time's offset from GMT, in either hours or minutes.
Alternately, use the UTCDate function to convert the
target time to the equivalent UTC date/time.
If timezone is left at null it
defaults to the timezone on the client.
You can also synchronise the client's time with that of the server.
Provide a callback function for the serverSync setting
that returns the current server time, usually from an AJAX call.
The example below is only a simulation.
Server synchronisation (simulated 5 mins ahead):
$('#syncCountdown').countdown(
{until: liftoffTime, serverSync: ahead5Mins});
function ahead5Mins() {
var server = new Date();
server.setMinutes(server.getMinutes() + 5);
return server;
}
In reality, you would have a program on the server responding with
the current time and connect a function that retrieved it and
presented it to the countdown. The following example uses a
simple PHP program to return the date/time in a format directly
usable by JavaScript. Remember to make the call synchronous
and to include the timezone in the response.
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
<?php
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Fri, 1 Jan 2010 00:00:00 GMT"); // Date in the past
header("Content-Type: text/plain; charset=utf-8"); // MIME type
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
Or the equivalent Java servlet fragment:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache, must-revalidate"); // HTTP/1.1
response.setHeader("Expires", "Fri, 1 Jan 2010 00:00:00 GMT"); // Date in the past
response.setHeader("Content-type", "text/plain; charset=utf-8"); // MIME type
String datetime = new SimpleDateFormat("MMM d, yyyy HH:mm:ss Z").format(new Date());
response.setHeader("Content-length", String.valueOf(datetime.length()));
response.getOutputStream().write(datetime.getBytes());
}
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:
$('#shortly').countdown({until: shortly,
onExpiry: liftOff, onTick: watchCountdown});
$('#shortlyStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown('option', {until: shortly});
});
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 or span.
You need to load the appropriate language package,
which adds a language set ($.countdown.regionalOptions[langCode]) and automatically
sets this language as the default for all countdown divisions.
Retrieve the current periods from a countdown timer.
Current periods:
$('#timesCountdown').countdown({until: longWayOff, format: 'YOWDHMS'});
$('#getNow').click(function() {
var periods = $('#timesCountdown').countdown('getTimes');
var text = '';
for (var i = 0; i < periods.length; i++) {
text += periods[i] + ' ' + $.countdown.regionalOptions[''].labels[i] + ' ';
}
$('#curPeriods').text(text);
});
Provides the jQuery Countdown plugin, along with a simple API function
(jquery_countdown_add) to easily add countdown/countup timer elements to the page.
There is a submodule called "jQuery Countdown Block" - that can be used
to provide one or more countdowns as a Block. It's very easy go to
"admin/build/block" and click on the local task "Add countdown block".
Now configure the countdown how ever you want. After save you have now a block
that can be placed on every region.
This site is all about writing stories together.
You can contribute as much or little as you wish but the idea is to
continue the theme and feeling of the story and most importantly
have some fun and help others to enjoy the experience too!
The countdown is used to time new contributions to the stories.
OnlineStudentPlanner.com helps students achieve their academic goals
by giving students tools to help them plan for their courses.
With OnlineStudentPlanner.com you will be able to keep track of your school
work, grades and appointments anywhere you are. By using the jQuery Countdown
plugin you will always know how many days are left in your semester.
PickTheBucket enables donors to give directly to projects supporting
vulnerable and disadvantaged children around the world. PickTheBucket is
operated by Global Care, a UK-based, Christian international children's charity.
PickTheBucket projects are operated by our international partners,
running childcare centres, schools, feeding and training programmes worldwide.
The countdowns apply to the various buckets available.
This extremely simple application allows you to maximize the
effectiveness of your team's time during meetings. By providing the total
number of participants and either their average hourly salary or average
yearly salary, we calculate exactly how much money per second that meeting
is costing your company/team.
2BTHR is a simple and fun web application allowing you to create an event by
entering a location and then using Google Maps to plot your destination.
You can then share the event with your friends and family via Twitter and Facebook!
Pennant Chase is a free baseball simulation website with over 600 active leagues.
Baseball fans can draft their teams based on real historical statistics.
The countdown is used in the private draft rooms to enforce picks in a timely manner.
League commissioners can set a desired timer length, and the countdown re-sets after each pick is made.
Ominder is simple and clean event reminder website where users can keep track of
their birthdays, anniversaries and much more. Ominder will notify users when
an event is about to occur so you never forget. The countdown timer is used
to show the user how much time is remaining until their event will occur.
To add another example, please contact me (wood.keith{at}optusnet.com.au)
and provide the plugin name, the URL of your site, its title,
and a short description of its purpose and where/how the plugin is used.
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({
labels: ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes', 'Seconds'],
// The expanded texts for the counters
labels1: ['Year', 'Month', 'Week', 'Day', 'Hour', 'Minute', 'Second'],
// The display texts for the counters if only one
compactLabels: ['y', 'm', 'w', 'd'], // The compact texts for the counters
whichLabels: null, // Function to determine which labels to use
digits: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], // The digits to display
timeSeparator: ':', // Separator for time periods
isRTL: false, // True for right-to-left languages, false for left-to-right
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 from
// 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
timezone: null, // The timezone (hours or minutes from GMT) for the target times,
// or null for client local
serverSync: null, // A function to retrieve the current server time for synchronisation
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
layout: '', // Build your own layout for the countdown
compact: false, // True to display in a compact format, false for an expanded one
padZeroes: false, // True to add leading zeroes
significant: 0, // The number of periods with values to show, zero for all
description: '', // The description displayed for the countdown
expiryText: '', // A message to display upon expiry, replacing the countdown digits
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
tickInterval: 1 // Interval (seconds) between onTick callbacks
});
$.countdown.regionalOptions[] // Language/country-specific localisations
$.countdown.setDefaults(settings) // Set global defaults
$.countdown.UTCDate(tz, time) // Standardise a date to UTC format
$.countdown.UTCDate(tz, year, month, day, hours, mins, secs, ms)
$.countdown.periodsToSeconds(periods) // Convert periods into equivalent seconds
$.countdown.resync() // Re-synchronise all countdown instances with their server
$(selector).countdown('option', options) // Change instance settings
$(selector).countdown('option', name, value) // Change a single instance setting
$(selector).countdown('option', name) // Retrieve instance settings
$(selector).countdown('destroy') // Remove countdown functionality
$(selector).countdown('pause') // Stop the countdown but don't clear it
$(selector).countdown('lap') // Stop the display but continue the countdown
$(selector).countdown('resume') // Restart a paused or lap countdown
$(selector).countdown('toggle') // Toggle between pause/resume
$(selector).countdown('toggleLap') // Toggle between lap/resume
$(selector).countdown('getTimes') // Retrieve the current time periods
Usage
Include the jQuery library (1.4+) in the head section of your page.
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.
Added substitutions to layout setting:
pnnn for periods with minimum three digits,
pd for individual digits of periods,
desc for countdown description,
sep for time separator