Handy code snippets

Handy code snippets
05 August 2005

Want to add a clock to your web page? Or inform site visitors when a page was last updated? Find out more…

You can do both of these tricks by adding the following concise JavaScript snippets to your page code.

To add a simple time feature paste this script into the Head tag of the page:

<script type="text/javascript">

var timer = null
function stop()
{
  clearTimeout(timer)
}

function start()
{
  var time = new Date()
  var hours = time.getHours()
  var minutes = time.getMinutes()
  minutes=((minutes < 10) ? "0" : "") + minutes
  var seconds = time.getSeconds()
  seconds=((seconds < 10) ? "0" : "") + seconds
  var clock = hours + ":" + minutes + ":" + seconds
  document.forms[0].display.value = clock
  timer = setTimeout("start()",1000)
}

</script>

Next, paste the code below into the <body> tag.

<body onload="start()" onunload="stop()">

Finally, add the code below where you want the clock to appear on the page.

<form>
    <input type="text" name="display" style="background-color: #E8EFFA; font: bold 10px verdana; width: 60px;">
</form>

One good reason to add a clock to your site is that it instantly tells site visitors the time zone in which you’re operating. With a .com domain, for instance, it is not immediately obvious where the company is based. It could just as easily be Aberdeen in Scotland or Aberdeen in South Dakota, a distance of some 2000 miles and a seven hour time difference, factors that will affect how quickly an order may be dispatched or an email enquiry answered.

Meanwhile, to add a ‘Page last updated’ feature paste the following code into the foot of the page:

Page last updated:

<script language="JavaScript">
  document.write(document.lastModified);
</script>

This small script informs users how up to date and relevant the information is. It sits best on a page that changes frequently or which contains time sensitive content. Avoid adding to pages that are static as it will then imply the site has gone into hibernation or worse.