Overview

The epiClock jQuery Plugin allows users to easily create dynamically updating clocks, timers, and stopwatches. Because of epiClock's ability to create and manage multiple clocks on a single page, the plugin provides the developer with both page level and element level management entry points. In addition, the plugin comes bundled with a prototyped Date object which allows the clock to format an output similar to that of PHP's date() function.

Quick-Start Guide

Each page must have a block type element to be used as a container for an epiClock.



   <body>
      <div id="clock"></div>
   </body>
   		

Each clock must be defined and configured after the dom loads. Then, the manager must be started.


			
  <head>
      <script type="text/javascript" src="script/jquery.min.js"></script>
      <script type="text/javascript" src="script/jquery.epiclock.min.js"></script>
      <script type="text/javascript">
         // Once the dom loads...	
         jQuery(function(){            
            jQuery('#clock')
                .epiclock()      // We define the clock...  
                .clocks(EC_RUN); // Then start the manager.
         });
      </script>
   </head>
   		
Remember to call jQuery.epiclock(EC_RUN) after you define your clocks, or they won't function!

jQuery Methods

epiClock provides users with two methods for creating and managing epiClocks. The Page Manager and the Element Manager. In addition, epiClock defines a Dynamic CSS Includer and Namespace, and a Namespace for custom clocks.

CSS Includer

The CSS Includer simply allows for dynamic loading by passing in a valid path to a css file.

cssInclude( path, [media ] )

If no value is passed in for media, "screen" will be used as a default.


  
  // Calling this will dynamically include the CSS file specified as if it were included at page load
  jQuery.cssInclude( '/path/to/style.css' );
 
        

Another related namespace in jQuery is created to track CSS includes done this way, to prevent duplicates. jQuery.cssIncludes is a hash of paths. If the path you specified is a key in this hash, the file has been included in this manner.

Custom Clocks

When defining custom clocks, they must extend jQuery.epiclocks. See Custom Rendering for more info.

The Page Manager

The Page Manager is a method which exists in the root level of jQuery. Users must invoke a call to the page manager to activate all clocks on the page. As of version 2.1, you can also access to page manager through the jQuery Element Function "clocks".


  
  // The Page Manager
  jQuery.epiclock( [ state, [ precision]] );
  // or Page Manager in a Chain
  jQuery('#selector').clocks( [ state, [ precision]] ).css( ... );
  
   		

state

Precision will only be applied when first calling with EC_RUN, or when calling EC_RUN after calling an EC_HALT.

precision

The number of milliseconds to poll for the time. Use the following as a guideline for setting precision:

The Element Manager

The Element Manager is a catch-all class which both creates and manages an epiClock on an element by element basis.


  
  // The Element Manager
  jQuery( '#clock' ).epiclock( ... );
   		
If no configuration options are passed to the Element Manager, a default clock will be created.

epiclock( options, [predefined ] )

As of epiClock 2.1, you can pass an optional second parameter to epiclock to use the default settings of a custom clock. See Custom Rendering for more info.

ParameterTypeDescription
modeSettingSets the type of epiClock to generate. See Clock Types for all the clock type options.
formatStringSets the output format of the epiClock. See Formatting Options for more info.
targetStringSome clock modes require a target datetime. See Clock Types for more info on the target parameter.
gmtBooleanIf set to true, the clock will calculate from Greenwich Mean Time, instead of localtime.
tplHTML SnippetAn HTML snippet used as the template for clock elements. By default, this is "<span></span>".
stylesheetStringIf this value is set to the path of a css file, epiClock will attempt to load this stylesheet after the clock has been setup.
containerClassStringIf set, epiClock will add the class(es) defined to the element which contains the clock.
offsetObjectAllows you to deform the clock's timer by any amount. Some clock modes require offset values to function. See Clock Types for more info.
{hours: 0, minutes: 0, seconds: 0, days: 0, years: 0}
arbitraryObjectAllows you to add an arbitrary number of days or years to the clock, which will be taken into account for rendering, but not for calculation. Useful for displaying datetimes beyond the scope of unixtime.
{days: 0, years: 0}
onTimerFunctionSome clock modes will fire the onTimer function once they have completed a countdown or timer. See Clock Types for more info.
onKillFunctionThe onKill function is called whenever a clock is destroyed. Firing an onKill callback is the last action an epiClock will take before destruction.
onRenderFunctionThe onRender function is called everytime the an output value changes. This can occur up to once every second. See Custom Rendering for more info.
onSetupFunctionThe onSetup function is triggered after the clock has been built. From within the onSetup function, "this" refers to the clock object.

epiclock( predefined )

Calling the element manager with the the name of a custom clock will use that clocks default settings with no user-defined options.

This is a new feature of epiClock 2.1. See Custom Rendering for more info.

epiclock( 'disable' )

Calling the element manager with the string 'disable' on an already configured clock will pause just that clock. Other clocks on the page will continue to function.

If the element has no valid epiClock, this method will do nothing

epiclock( 'enable' )

Calling the element manager with the string 'enable' on an already disabled clock will pause just that clock. Other disabled clocks will remain disabled.

If the element is not a disabled epiClock, this method will do nothing

epiclock( 'destroy' )

Calling the element manager with the string 'destroy' on an already configured clock will pause destroy that clock. Other clocks on the page will continue to function.

Once a clock is destroyed, it CANNOT be recovered!

epiclockQuery( format )

Accepts a formatting string like the one passed into the element manager at the time of clock creation. When this method is called on an epiClock element, it will return the current time, formatted in whatever format is provided to this function.

Clock Types

Setting NameTargetonTimerOffsetDescription
EC_CLOCKCan offset any clock value to alter calculation.A standard clock which displays the current local time.
EC_COUNTDOWNClock calculates the time until the target dateFires when the target date arrives, then dies.Can offset any clock value to alter calculationA timer which displays the amount of time left until the target date. Displays all zeroes once date arrives.
EC_COUNTUPClock calculates the time since the target dateCan offset any clock value to alter calculation.A timer which displays the amount of time past since the target date.
If the target date has not yet occured, the clock will display negative numbers!
EC_HOLDUPClock calculates the time since the target dateCan offset any clock value to alter calculation.A timer which displays the amount of time past since the target date. Unlike countup, will display all zeroes if target has not arrived.

EC_ROLLOVERClock calculates the time until the target, then the time since the targetFires when the target date arrives, then starts counting up.Can offset any clock value to alter calculation.A timer with functionality identical to an EC_COUNTDOWN clock if the target date is in the future, or an EC_COUNTUP clock if the target date is in the past.
EC_EXPIREFires when the offset value has been overcome, then dies.Set a positive value to any offset to add that value to the timer.A timer which counts off any values entered in offset, then dies.
EC_LOOPFires when the offset value has been overcome, then resets to the initial value.Set a positive value to any offset to add that value to the timer.A timer which counts off any values entered in offset, then resets to the max value.
EC_STOPWATCHOffsets the starting value of the stopwatch.A timer which displays the number of seconds the timer has been active on the page.
Unlike other settings, the stopwatch will tear on a pause, meaning if paused after 3 seconds for 6 seconds, then restarted, the clock will resume counting up from 3.

Formatting Options

When creating a new clock, you must provide a formatting string to tell epiClock how you want the output to be rendered. Using formatting is pretty simple:

Default Formatting String

Each clock type comes with a default formatting string. You can overwrite the default by specifying your own string in the options Object passed to an epiClock.
Clock TypeDefault StringExample Return Value
EC_CLOCK'F j, Y, g:i:s a'March 10, 2001, 5:16 pm
EC_COUNTDOWN'V{d} x{h} i{m} s{s}'3d 04h 05m 06s
EC_COUNTUP'Q{y} K{d} x{h} i{m} s{s}'2y 3d 04h 05m 06s
EC_HOLDUP'Q{y} K{d} x{h} i{m} s{s}'2y 3d 04h 05m 06s
EC_ROLLOVER'V{d} x{h} i{m} s{s}'3d 04h 05m 06s
EC_EXPIRE'x{h} i{m} s{s}'04h 05m 06s
EC_LOOP'i{m} s{s}'05m 06s
EC_STOPWATCH'x{h} C{m} s{s}'04h 05m 06s

Formatting Characters

Format CharacterDescriptionExample Return Value
Arbitrary Values
EThe number of arbitrary days set for the timer, without leading zeroes. If the number of days increase/decrease as the clock runs, will increase arbitrary days.3
eThe number of arbitrary days set for the timer, with a leading zero.03
QThe number of arbitrary years set for the timer.1
Custom Timers
VThe number of days on the timer3
vThe number of days on the timer, padded to two digits.03
KThe number of days on the timer, offset by years.366 becomes 1
kThe number of days on the timer, offset by years, padded to two digits.366 becomes 01
XThe number of hours on the timer4
xThe number of hours on the timer, padded to two digits04
CThe number of minutes on the timer, padded to two digits08
pThe number of minutes on the timer8
Days
dDay of the month, 2 digits with leading zeros01 to 31
DA textual representation of a day, three lettersMon through Sun
jDay of the month without leading zeros1 to 31
l[ lowercase "L" ] A full textual representation of the day of the weekSunday through Saturday
NISO-8601 numeric representation of the day of the week1 (for Monday) through 7 (for Sunday)
SEnglish ordinal suffix for the day of the month, 2 characters. Works well with jst, nd, rd or th.
wNumeric representation of the day of the week0 (for Sunday) through 6 (for Saturday)
zThe day of the year (starting from 0)0 through 365
Week
WISO-8601 week number of year, weeks starting on Monday42 (the 42nd week in the year)
Month
FA full textual representation of a month, such as January or MarchJanuary through December
mNumeric representation of a month, with leading zeros01 through 12
MA short textual representation of a month, three lettersJan through Dec
nNumeric representation of a month, without leading zeros1 through 12
Year
LWhether it's a leap year1 if it is a leap year, 0 otherwise
YA full numeric representation of a year, 4 digits1999 or 2003
yA two digit representation of a year99 or 03
Time
aLowercase Ante meridiem and Post meridiemam or pm
AUppercase Ante meridiem and Post meridiemAM or PM
BSwatch Internet time000 through 999
g12-hour format of an hour without leading zeros1 through 12
G24-hour format of an hour without leading zeros0 through 23
h12-hour format of an hour with leading zeros01 through 12
H24-hour format of an hour with leading zeros00 through 23
iMinutes with leading zeros00 to 59
sSeconds, with leading zeros00 to 59
uMicroseconds. Unreliable due to polling speed.54321
Timezone
ODifference to Greenwich time (GMT) in hours+0200
PDifference to Greenwich time (GMT) with colon between hours and minutes+02:00
ZTimezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.-43200 through 50400
Full Date/Time
cISO 8601 date2004-02-12T15:19:21+00:00
rRFC 2822 formatted dateThu, 21 Dec 2000 16:01:07 +0200
USeconds since the Unix Epoch (January 1 1970 00:00:00 GMT)2959487

Adding Custom Formatting Characters (Advanced)

Users who wish to add custom functionality to the formatting engine need only to prototype their character into the Date native as a function.


			
   Date.prototype.J = function(){   // Multiplies the Day of the Week (0-7) by 10.
      return this.getDay() * 10;		
   }
		

Now, this user could pass "w * 10 = J" into epiClock as a formatting string. Assuming it's tuesday, the output would be:

			
   2 * 10 = 20
		

The Rendering System

When a new epiClock is created by the Element Manager, the formatting string is converted into span tags with different classes. As the clock runs, it continually computes the new values for each formatting character. Then, the rendering engine passes the element to be updated along with the new value to the rendering function.

This method allows users to override the default rendering function to create fully customized outputs (far surpassing merely styling the clock with CSS).

As of epiClock 2.1, you can define a tag other than the default <span></span> by setting the option value of "tpl" to the HTML snippet you wish to use.

The onRender Callback


			
   function(el, value){
      el;    // a jQuery object for the element that needs updating
      value; // The new value for the object
   }
		
The onRender callback is fired only when the object actually needs updating. Custom rendering functions should therefore leave out any logic to determine if the value should be updated, and just update it.

The Default Rendering Function


			
   function(el, value){
      el.html(value);
   }
		

Using Custom Rendering Engines

By default, all epiClock Rendering Engines should exist inside of the epiclock/clocks/ directory, and follow the naming scheme epiclock.clockname.js. This directory should also hold any of the custom stylesheets or spirte sheets used in rendering clocks.


            
  <head>
      <script type="text/javascript" src="script/jquery.min.js"></script>
	  <script type="text/javascript" src="script/jquery.epiclock.min.js"></script>
      <script type="text/javascript" src="script/clocks/epiclock.retro.min.js"></script>
      <script type="text/javascript">
         // Once the dom loads...   
         jQuery(function(){            
            jQuery('#clock')
                .epiclock('retro) // We define the clock...  
                .clocks(EC_RUN);  // Then start the manager.
         });
      </script>
   </head>
        
Note: Be sure to include the core epiClock plugin before any custom rendering engines. Not doing so will cause the engine to be unavailable, and will result in errors being thrown.

The Retro Flip Clock Rendering Engine

The following is a custom rendering engine which comes packaged with epiClock. It contains all the logic needed to display a reto flip clock. (The images are also packaged with the core library)


			
   jQuery.extend(jQuery.epiclocks, {
        retro: {
            format: 'h:i:s a',
            stylesheet: 'clocks/retro.css',
            containerClass: 'epiclock-retro',
            tpl: '<div></div>',
            innerTpl: '<div class="epiclock-img"></div>',
            onSetup: function(){
                jQuery('.epiclock-retro .epiclock-img').live('flip-clock', function(){
                    var el = $(this);
                    setTimeout(function(){ 
                        el.removeClass('a1').addClass('a2');
                        setTimeout(function(){ el.removeClass('a2').addClass('s') }, 150);
                    }, 150);
                });
            },
            onRender: function(el, val){
                var digits = val.substring(1) == 'm' ? [val] : val.split('').reverse(),
                    last = el.data('last'),
                    prefix = last ? 'd' : 's',
                    cmp = last ? last.split('').reverse() : [],
                    img = jQuery.makeArray(jQuery('.epiclock-img', el)).reverse(),
                    clock = this;
                    
                jQuery.each(digits, function(i,v){
                    if (v == cmp[i]) return;
                    jQuery(img[i] || jQuery(clock.innerTpl).prependTo(el))
                        .removeClass('s d'+cmp[i])
                        .addClass('d' + v + ' a1')
                        .trigger('flip-clock');
                });
            }
        }
    });
		

About Custom Rendering

As of epiClock 2.1, custom rendering has become a bit more automated to help make them easier to use and more efficient.

One of the new features added to help achieve this goal is the jQuery.epiclocks object. By extending this and naming our rendering function, we can easily implement the styles in a clock like so:


   
   // Calling the Element Manager with this optional second property will tell epiClock to try and load 
   // a clock named "retro" from the "jQuery.epiclocks" object.
   jQuery('#clock').epiclock({gmt: true}, 'retro');
        

If you wish to invoke a custom clock without any options, you can simply pass in the clock's name.


   
   // Calling the Element Manager with just the clock name will create a non-user configured clock
   // and will use just the default settings provided in the clock definition.
   jQuery('#clock').epiclock('retro');
        

Custom Styling

When the Element Manager first parses the formatting string, it converts the caracters to tags with special classes. A quick example:

The formatting string "Q {years} K{days} x:i:s" becomes:


			
   <div id="clock">
      <span class="epiclock epiclock-digit"></span>
      <span class="epiclock epiclock-spacer"></span>
      <span class="epiclock">years</span>
      <span class="epiclock epiclock-spacer"></span>
      <span class="epiclock epiclock-digit"></span>
      <span class="epiclock">days</span>
      <span class="epiclock epiclock-spacer"></span>
      <span class="epiclock epiclock-digit"></span>
      <span class="epiclock epiclock-separator">:</span>
      <span class="epiclock epiclock-digit"></span>
      <span class="epiclock epiclock-separator">:</span>
      <span class="epiclock epiclock-digit"></span>
   </div>
		

The resulting output looks something like this:

			
   	2 years 3days 04:05:06
		

Class Info

As of epiClock 2.1, tags will no longer use the invalid "ref" attribute. If you wish to know what encoding character was used to create the element, use:

   
   // Assume we call this, given the example above
   jQuery('.epiclock-digit:eq(2)').data('ec-encoding');  // Will return "x"
        
<
ClassDataDescription
epiclockGeneric style indicating the element was created by epiclock
epiclock-spacerA space (default stylesheet ascribes a left/right margin of 5px)
epiclock-separatorContains a single non-formatting character not between curly braces.
epiclock-digitContains a computed clock value for the formatting character used to create the container.

Live Demo

Please visit: http://eric.garside.name/demo.html?p=epiclock

Current Downloads

The current version of epiClock can be downloaded from Google Code

Subversion

You can also checkout the subversion repository for epiClock with the following command:

			
   svn checkout http://epiclock.googlecode.com/svn/trunk/ epiclock-read-only