Unobtrusive JavaScript Dynamic Clock

Published Tuesday, March 4, 2008 @ 10:49 am • 5 Responses

[ ~{*}~ ] In this tutorial, I present an easy way to add a little extra flair to your site by adding some dynamic clock functionality. Using unobtrusive JavaScript, a bit of (X)HTML markup, and a dash of PHP (optional), we will create a dynamic clock that degrades gracefully to a static date/time-stamp when JavaScript is unavailable. No need to get all verbose with this one, so let’s dive right in..

Step 1: The JavaScript

Place the following code into a JavaScript file called “xClock.js” (or whatever) and upload to your server:

// Unobtrusive JavaScript Dynamic Clock
// http://perishablepress.com/press/2008/03/04/unobtrusive-javascript-dynamic-clock/

function xClock() {
   xC = new Date;
   xV = vClock(xC.getHours()) + ":" + vClock(xC.getMinutes()) + ":" + vClock(xC.getSeconds());
   document.getElementById("xClock").innerHTML = xV;
   setTimeout("xClock()", 1000);
}
function vClock(v) {
   return (v > 9) ? "" + v : "0" + v;
}

// addLoadEvent @ http://simonwillison.net/2004/May/26/addLoadEvent/

function addLoadEvent(func) {
   var oldonload = window.onload;
   if (typeof window.onload != 'function') {
      window.onload = func;
   } else {
      window.onload = function() {
         if (oldonload) {
            oldonload();
         }
         func();
      }
   }
}
addLoadEvent(xClock);

The first portion of the code comprises the dynamic clock, while the second portion is an extremely useful “addLoadEvent” function provided by Simon Willison. After the web page has loaded, the addLoadEvent function will execute the xClock function. Next, let’s add some markup..

Step 2: The Markup

This specifics of this step will vary depending on your desired page layout, but essentially we want to create an empty <span> or <div> (or whatever) and give it an id="xClock", like so:

<span id="xClock"></span> will output this: (after completion of step #3)

Simply place an empty <span> with an id="xClock" wherever you would like the dynamic clock to be displayed. For example, you could place the target element in your sidebar using something similar to the following:

<h4><?php echo date("l, F j, Y ~ "); ?><span id="xClock"></span></h4>

This code does a couple of things. In the first line, we begin by wrapping the clock output in warm & fuzzy <h4> heading. We then use PHP to echo the date, which is formatted as “Weekday, Month Day, Year”. The date information is then proceeded by the required element for the dynamic xClock itself (i.e., <span id="xClock"></span>). The end result would present todays date and current time as:

Tuesday, March 4, 2008 ~

Of course, as completely unobtrusive code, the xClock functionality degrades gracefully when JavaScript is unavailable — the clock simply disappears! This is why echoing the date via PHP is good idea. It ensures that some chronological information is displayed even when the dynamic clock is unavailable. Of course, if you wanted to get really fancy, you could use a little <noscript> action to echo a static instance of the hour, minute and second that the page was created. Adding this to our previous example, we get:

<h4><?php echo date("l, F j, Y ~ "); ?><span id="xClock"></span> 
<noscript><?php echo date("h:i:s", time(); ?></noscript></h4>

..which, when JavaScript is unavailable, will output the following static date and time:

Tuesday, March 4, 2008 ~ 11:33:07

The only difference between this non-JS output and the previous, JS-enabled output is the dynamic property of the clock. Not too shabby!

Step 3: Call the Script

Finally, we need to call the xClock.js script itself by placing the following element into the <head> or footer section of your document:

<script src="http://domain.tld/js/xClock.js" type="text/javascript" ></script>

Once this is in place, load the target page in a browser and check that everything is working. If everything went according to plan, your site should now be sporting a new dynamic clock for all the world to see. You may also want to disable JavaScript in your browser and check the formatting of the static timestamp. If needed, it is also possible to adjust the default “timeout” setting, which is currently set at 1000 ms. With a little imagination, the layout/design possibilities for adding a sense of time to your blog are endless! That’s all for now, stay tuned for more unobtrusive JavaScript tips and tricks arriving soon! ;)


Dialogue

5 Responses Jump to comment form

1Gordon

March 5, 2008 at 1:41 pm

Is there any way to use this code to display st, nd, rd or th after the date i.e. 1st, 2nd, 3rd or 4th March 2008 ?

2Perishable

March 5, 2008 at 3:22 pm

As is, this script does not include any “user-friendly” date formatting. Here is an excellent tutorial that provides plenty of in-depth JavaScript date-formatting techniques. I hope that helps!

3teddY

March 16, 2008 at 1:02 am

Hey Jeff thanks for sharing the script :) I find it very light and handy, as compared to other ones available on line. Oh and thanks for explaning what the script does in the post, I guess very little people do so (and they usually just dump the code in a post and tell you where to paste it, that’s all).

Thanks!

4Perishable

March 16, 2008 at 4:16 pm

Absolutely my pleasure, teddY! I agree that posted code should always include some sort of explanation, even for “basic” scripts such as this one. Not only does it help other users, but I think it benefits the writer as well — I am always surprised at how much I don’t really know! ;)

5Levski

July 13, 2008 at 7:17 am

Excellent! This is definitely better than using Java based clocks :)

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

mmmm, dark chocolate..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Nyx: Happy to have helped! Love your site....
  • dockside: Hi i want to use this code on my blog. but not for all post. I want 3 or 4 full posts and then post in double column How?...
  • NZ Beats: Got it working using the following: http://www.nzbeats.com/?feed=rss2&category_name=album-review...
  • Paul: Holy crap, you just saved my A$$! Thank you!...
  • free games: Google have a content distribution network here http://code.google.com/apis/ajaxlibs/documentation/#AjaxLibraries where you ca...
  • free games: Found this (untested) for those that just want https For HTTPS: var pageTracker = _gat._getTracker("UA-XXXX-1"); pageTracker...
  • H5N1: The question is very hard. No way to solve it in only few words :) First of all you need a Linux. OK. But Linux it's only a Kerne...
  • gowers: wow, your theme is so great, I like it...
  • Eric Ferraiuolo: Like some people are commenting, a virtual solution is going to be the easiest to get going with the least number of issues. I would ...
  • Brent Terrazas: Thanks for the mention, I currently am running Ubuntu Server 8.04 on VMWare Fusion beta (it's a free beta download.. check it out fo...

Read more recent comments..