SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Ticking Clock
By Scott Isaacs

Create a live ticking clock anywhere within your HTML page.

The Current Time is:

The clock only ticks in Internet Explorer 4.0.

Description

To create the clock, an element with the ID of "clock" is created on the page. This element is updated each second with the current time. In browsers that do not support Dynamic HTML, but do support JavaScript, the time the page is loaded is rendered by inserting the current time into the page when it is loaded:

  <SPAN ID=clock>
    <SCRIPT Language=Javascript>
    //down-level script support - outputs an initial static time
      document.write(buildTime())
    </SCRIPT>
  </SPAN>

Code

  // Check if IE4 or greater.
  var MS=navigator.appVersion.indexOf("MSIE")
  window.isIE4 = (MS>0) && (parseInt(navigator.appVersion) >= 4)

  function lead0(val) {
    // add leading 0s when necessary
    return val<10 ? "0"+val.toString() : val
  }

  function buildTime() {
    var time = new Date()
    var ampm = "AM"
    var h=time.getHours()
    // fix military time and determine ampm
    if (h > 12) {h = h - 12; ampm = " PM";}  
    return h+":"+lead0(time.getMinutes())+":"+ lead0(time.getSeconds()) + ampm
  }

  function tick() {
    // Replace the plain-text contents of the clock element
    document.all.clock.innerText = buildTime()
  }    

  // Start clock when page is loaded.
  window.onload = new Function("if (window.isIE4) setInterval('tick()',1000)")
Discuss and Rate this Article