SiteExperts.com Logo Home | Community | Developer's Paradise
High-Tech Jobs | User Groups | Site Information

DHTMLLib Demos/ Dynamic Text

Creating a real clock is simple. All positioned elements expose an innerHTML property. Assigning HTML to this property immediately updates your page. For example, the current time is:

Most of the clock's script is spent formatting the string. The actual assignment to display the clock is 1 line of code:

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 contents of the clock element
  // In the page there is a <SPAN ID="clock" STYLE="position: absolute">
  // document.all.clock accesses this element.
  document.all.clock.innerHTML = buildTime()
}    

function doLoad() {
  setup()
  setInterval("tick()",900)
}
window.onload = doLoad;

For more fun, try typing HTML into the textbox below. With a single line of script on the Display HTML button, document.all.eOutput.innerHTML = this.form.tOutput.value, you can update the HTML on your page.