Webmaster Resources Center

Welcome to the Bravenet Resource Center. Use these resources to help make your web pages more advanced and fun to use.

Articles & Tutorials

JavaScript Clock

by Daniel Insley


Summary : Here is a fun JavaScript clock to add to your website. This script is easy to install.

The following JavaScript clock is easy to install and allows you to display the current hour, minute and second of the time. Unlike previous versions of this script, the script will work in Internet Explorer, Netscape Navigator, and Mozilla. All you have to do is paste this code into the section of your website...

<script type="text/javascript">
function createtime()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var abbrev = "AM"
if (hours>=12)
abbrev="PM"
if (hours>12)
{
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
var ctime=""+hours+":"+minutes+":"+seconds+" "+abbrev+""
if (document.all)
document.all.clock.innerHTML=ctime
else if (document.getElementById)
document.getElementById("clock").innerHTML=ctime
else
document.write(ctime) }
if (!document.all&&!document.getElementById)
createtime()
function loadtime()
{
if (document.all||document.getElementById)
setInterval("createtime()",1000)
}
</script>

With that in the HEAD section of your website, place onLoad="loadtime()" inside your body tag like shown, but don't add the body tag if you already have a body tag!

<body onLoad="loadtime()">

Finally, add this empty span to where you would like the clock to show up in your website:

<span id="clock"></span>

The span can be style with CSS to be visually enhanced. Save your changes and enjoy your new clock!