Unobtrusive JavaScript Dynamic Clock

Published Tuesday, March 4, 2008 @ 10:49 am • 7 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

7 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 :)

6Bill Brown

November 29, 2008 at 1:53 pm

I’m curious about your use of the (increasingly unpopular) noscript tag. Couldn’t you simply populate span#xClock with the time from PHP and overwrite it with the new time from JavaScript? Barring that, couldn’t you also simply add something like:

<span id="yClock"><?php echo date("h:i:s", time(); ?></span>

…and then remove this element in your init function:

var yClock = document.getElementById('yClock');
yClock.parentNode.removeChild(yClock);

7Jeff Starr

November 30, 2008 at 10:23 am

Excellent tips, Bill! I will have to implement them during the next update! Thanks for sharing :)

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

better to have too many ideas and not enough time than the converse

Perishable on Tumblr

WordPress Tip for Multiple Themes

Sunday, 4 January 2009, 5:16 pm

If your site makes available multiple themes for users to choose from, remember to include the JavaScript (or any other required code) for any statistical applications that you might be using, such as Mint, Google Analytics, and so forth. I am not sure about the various WordPress statistics plugins, but they may need to be included as well. A good way to check if your stats plugin is tracking data across all themes is to either visit a few pages that you know others aren’t hitting, or else activate each of the alternate themes and check the source code of each one for the required code.

Earlier today, I realized that only several of my most recent themes included the required JavaScript for Mint and Google Analytics. I am now in the process of editing each of the 18 themes available for users at Perishable Press. Haven’t decided on whether or not both statistics apps are needed for all themes, but I will certainly be using at least one of them to keep an eye on everything.

Insane Christmas

Monday, 22 December 2008, 9:47 pm

For as long as I can remember, Christmas has always been a relatively peaceful affair. Sure there’s the usual holiday stress — traffic, shopping, presents, relatives, and all that goes with the preparation of a traditional celebration, but when it’s all said and done, you get to relax and enjoy the peace and harmony of gathering together and basking in the reason for the season: the birth of Christ.

This year, however, the stress factor has been kicked up a few notches, making for a rather insane Christmas if I do say so myself. In addition to the usual holiday chaos, we are currently purchasing a brand new home, and quickly realizing the incredible amount of work involved in the process. If you’ve ever bought a newly built home, you know exactly what I am talking about here.

Plus, as if all the paperwork, inspections, insurance, costs, and anxious anticipation weren’t enough to confound the usual holiday stress, we are also packing up everything, dealing with kids, working full-time jobs, and — beginning on Christmas Eve — moving into our new house.

It certainly is all a great joy and blessing to have such amazing things going on, but combined with the work that I do on the Web — blogging, designing, projects, helping people, and so on — it really becomes all too much rather quickly. We are doing are best to get through everything with our sanity intact, but I have to admit that this is the most insane Christmas I have ever experienced.

New (4G) Blacklist Now in Beta

Monday, 22 December 2008, 9:27 pm

Just a quick note to anyone interested in securing their websites against malicious activity, spam, and other nonsense. Several months after releasing my 3G Blacklist, I have finally begun work on the next incarnation of the blacklist: the 4G Firewall!

The first part of the blacklist is now ready for testing, and I plan on setting it up on Perishable Press within the next few days. While testing on my own site, I thought it would beneficial to also invite a few “beta” testers to run the code on their own site(s) as well.

So, if you have a site that receives its share of malicious attacks, and cracker exploits, drop me a line via the contact form at Perishable Press and I will send you the initial block of HTAccess directives. This version of the Blacklist is looking better than ever, and I look forward to releasing the complete version to the public early in 2009.

Thanks for the Free Traffic and Link Juice

Sunday, 7 December 2008, 1:26 pm

Just wanted to thank the fine folks at fafich.ufmg.br for all the free traffic and link juice. Thanks to their misapplication of my comprehensive canonicalization code, every non-canonical version of their 21,700 indexed pages points directly to my site, Perishable Press. This means that every one of their permalink URLs that is mistyped, lacks the “www” prefix, or contains the superfluous “index.php” file name is directed via permanent redirect directly to the home page of my site.

I have tried contacting the site owner(s) about this situation, but it has been over a week and I have yet to hear anything back. Hopefully, they will take notice soon and correct the issue by properly configuring their htaccess file, but in the meantime, I certainly don’t mind the extra link juice and free traffic! :)

No Plugin Needed for Feed Delay

Monday, 24 November 2008, 10:01 am

I recently saw a WordPress plugin that was designed to delay the publication of your WordPress feed by any specified time interval. While it is a good idea to carefully proofread your content before posting it, a plugin certainly is not required to do so.

As savvy WordPress users already know, WordPress has a built-in post-preview feature that enables authors to view their unpublished content as a published post. This enables authors to do any amount of proofreading and browser checking until they are satisfied with the results.

To do this, simply write your post as usual, and then click on the “Preview this post” button on the right-hand side of the screen. In older versions of WordPress (less than 2.5, I think), you actually need to save (without publishing!) the post first and then re-open it as if to continue editing. You will then see a “Preview »” link sort of hidden (due to poor CSS design) in the upper-right corner near the edit post field. Right-click on that link to open in new tab and you are good to go.

No extra plugin needed! :)

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Jeff Starr: Hi heywho, glad to hear you are doing well! ;) I wish I could join in the festivities.. it has been so long that I almost have forgot...
  • Rob Barrett: Thanks for posting about the Stealth Publish plugin -- just what I needed for my site. Works perfectly!...
  • Jeff Starr: Hi Chiwan, I got your email and have sent some information that may help you with this. Cheers, Jeff...
  • Chiwan: Hi. This is cool. So I can I replace the clock that comes with your Apathy theme with this clock? If that's not possible, how do ...
  • Brass Engraved: Thankyou very much for this, worked like a dream!...
  • Patrix: I'm using FeedBurner and the Feedsmith plugin for my filter blog, DesiPundit. I found your post via the WordPress page for RSS feeds ...
  • teddY: @Jessi Hance: Sorry to hear about your experience with Twitter spammers/flamers. I was once a victim of flamers and it sucks that peo...
  • heywho: Hey.... Very Nice...... I'm TOTALLY not a programmer..... but I have this thing I want to do...... so I just decided to start doi...
  • Rodrigo Nunes: NIce SEE MY BLOG http://designrn.wordpress.com/...
  • zubfatal: The Quintessential theme looks great to me, however when scrolling up or down on the page, it makes my laptop work harder than it sho...

Read more recent comments..

Attention: Do NOT follow this link!