Simon & Matt's new Photoshop book is out now!

Photoshop CS3 Layers Bible book cover

Sharpen your Photoshop skills today!

PageKits.com Featured PageKits

Clear Thinking PageKit
Clear Thinking ($44.99)


White Tip PageKit
White Tip ($44.99)


See more! > >

 

How-To: Creating a JavaScript clock

Level: Intermediate. Published on 20 February 2007 in JavaScript

In this how-to, we use JavaScript's Date object and Window.setInterval method to make a simple real-time clock that you can place on any Web page. Along the way, we'll take a look at how to access text nodes in the DOM, and how to set an onLoad event handler.

One of the great things about JavaScript is that it lets you manipulate the contents of a Web page in real-time. This means that we can use JavaScript to create a digital clock, embedded in the Web page, that updates every second. This article shows you how to do just that.

Getting the current time

If we want to create a clock then obviously we need to retrieve the current time. We can do this via JavaScript's Date class. First, we create a new Date object with no parameters, which gives us a Date object containing the current date and time on the visitor's computer:


var currentTime = new Date ( );

Next, we extract the hours, minutes and seconds components of the current time from our Date object:


var currentHours = currentTime.getHours ( );
var currentMinutes = currentTime.getMinutes ( );
var currentSeconds = currentTime.getSeconds ( );

Formatting the time

Now that we have the three component values of our current time, let's format them into a nice string for displaying in the Web page. We want it to be in the format "HH:MM:SS XX", where XX is either "AM" or "PM" (assuming we're after a 12-hour clock format).

First we'll add a leading zero to the minutes and seconds values, if required:


currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

The ? and : symbols used above comprise the ternary operator. This is a special operator that returns the value before the colon if the condition before the query (?) is true, or the value after the colon if the condition is false. It's a great way to write an if block in shorthand, provided you only need to return a single value.

Next we'll set a variable, timeOfDay, to "AM" or "PM" as appropriate, and subtract 12 from the hours component, if required, to convert it to 12-hour format. We'd also like the hours component to show 12 rather than 0, so we need to add a check for this too:


var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";
currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;
currentHours = ( currentHours == 0 ) ? 12 : currentHours;

Finally, we'll join all our formatted components together into a single string, in the format "HH:MM:SS XX":


var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

Displaying the clock

Now that we have our time string ready for display, the next step is to display it in the Web page. To do this, we first create a span container in the markup to hold the time display:


<span id="clock">&nbsp;</span>

By placing the &nbsp; inside the span element, we're creating a textNode child node for the span. We can then populate the container with our time string by retrieving this child textNode then setting its nodeValue property, as follows:


document.getElementById("clock").firstChild.nodeValue = currentTimeString;

Putting it all together

Here's our finished JavaScript code, ready to be placed in the head element of the Web page. We've wrapped all the above code in a JavaScript function, updateClock():


<script type="text/javascript">
<!--

function updateClock ( )
{
  var currentTime = new Date ( );

  var currentHours = currentTime.getHours ( );
  var currentMinutes = currentTime.getMinutes ( );
  var currentSeconds = currentTime.getSeconds ( );

  // Pad the minutes and seconds with leading zeros, if required
  currentMinutes = ( currentMinutes < 10 ? "0" : "" ) + currentMinutes;
  currentSeconds = ( currentSeconds < 10 ? "0" : "" ) + currentSeconds;

  // Choose either "AM" or "PM" as appropriate
  var timeOfDay = ( currentHours < 12 ) ? "AM" : "PM";

  // Convert the hours component to 12-hour format if needed
  currentHours = ( currentHours > 12 ) ? currentHours - 12 : currentHours;

  // Convert an hours component of "0" to "12"
  currentHours = ( currentHours == 0 ) ? 12 : currentHours;

  // Compose the string for display
  var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;

  // Update the time display
  document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}

// -->
</script>

To make the clock update every second, we need to use the Window.setInterval() method from within the page's body tag to call our updateClock() function once per second. (For more on setInterval, see our tutorial on setTimeout and setInterval.) We should also call updateClock() at the moment the page loads, so that the clock appears straightaway:


<body onload="updateClock(); setInterval('updateClock()', 1000 )">

That's it! You can see the clock in action on this demo page. We've also added some CSS to the clock container to make it prettier.

Feel free to use any of the above JavaScript code to make a clock for your own website. You might like to try putting the various time components in separate span containers, so that you can style them individually. You could also try converting the code to display a 24-hour clock instead. Have fun!

The end

That's the end of this article. We hope you found it useful. If you're still stuck and would like further help, check out our online Help Forums, where you can get assistance from members of Elated and other webmasters.

Also, don't forget the free ELATED Extra Newsletter, where you can get more great Web-building articles and tips sent straight to your inbox!

If you would like to offer us feedback on this or any of our articles, please contact us. Have fun!

Top of Page

Sign up to our newsletter

and get free goodies!