Latest TweetsWordPress and the Blank Target Vulnerability (aka rel noopener + noreferrer): perishablepress.com/wordpress-… #WordPress #security #html
Perishable Press

Unobtrusive JavaScript Dynamic Clock

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..

Demo

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
// https://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;
}

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. After the web page has loaded, the addLoadEvent function will execute the xClock function.

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>

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:

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

This code does a couple of things. In the first line, we begin by wrapping the clock output in warm & fuzzy <p> 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, for example:

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

As you can see in the demo, the time is dynamic, so the user will see the numbers change as each second passes.

Graceful Degradation

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:

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

When JavaScript is unavailable, this will output the following static date & 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!

Download

Here you may download the source files for this tutorial/demo:

That’s all for now, stay tuned for more unobtrusive JavaScript tips and tricks arriving soon! ;)

Jeff Starr
About the Author Jeff Starr = Web Developer. Book Author. Secretly Important.
Archives
11 responses
  1. 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 ?

  2. Jeff Starr

    As is, this script does not include any “user-friendly” date formatting. Here is an excellent tutorial (404 link removed 2017/01/20) that provides plenty of in-depth JavaScript date-formatting techniques. I hope that helps!

  3. 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!

  4. Jeff Starr

    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! ;)

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

  6. 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);

  7. Jeff Starr

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

  8. Peter Assenov February 13, 2009 @ 7:21 am

    Very nice script, thanks for sharing it!
    If I may propose a “compressed” version… :)
    The contents of “xClock.js” could be:

    function xClock() {
         setInterval("document.getElementById('xClock').innerHTML=new Date().toLocaleTimeString()",1000)
    }
    function addLoadEvent(func)
    { (window.attachEvent)? attachEvent('onload',func) : addEventListener('load',func,false);
    }
    addLoadEvent(xClock);

    All the rest is as described in the tutorial.

  9. Jeff Starr

    Hi Peter, thanks for that tasty tip! It is sweet having an alternate version of the JavaScript Clock to play with. Your version is much cleaner and to the point. I have to admit that JavaScript is not my strong suit! Thanks for sharing :)

  10. The only problem is that the clock displays in the 24-hour format. What if you want to display in 12-hour format instead, with AM/PM indicated, along with the timezone for the current user (such as EST or EDT)?

  11. Bill Brown April 15, 2009 @ 6:58 am

    @Shefik: here you go.

[ Comments are closed for this post ]