Javascript Clock Demo

The Javascript Clock Demo provides an example of how to display the time on a web page using javascript. On this page, I also demonstrate techniques for rendering dynamic HTML using "getDocumentById().innerHTML".

Instructions

Click on the Show Time link below and the time will be displayed and a link named Hide Time will appear. Click on the Hide Time link and the clock disappears and the Show Time link comes back. You can toggle this back and forth as many times as you wish, as the HTML inside the "showHide" id is just replaced.


Source Code

To implement this on your webpage requires a few lines of java script. Please note that I am using the DOJO fade in effect above, which is optional and not included in the source code below.

    <html>
    <head>
        <title>Javascript Clock Demo</title>
    <style type="text/css">
        .clock {
            font-family: Verdana, Hevletica, sans-serif;
            background: transparent;
            border-style: none;
            color: #d2691e;
            font-size: 1em;
            font-weight: bold;
            text-align: left;
        }
    </style>
    <script type="text/javascript">
        var showHide = "hide";
        function showFilled(Value) {
            return (Value > 9) ? "" + Value : "0" + Value;
        }
        function startClock() {
            theTime = new Date;
            if (document.getElementById("showTime")) document.getElementById("showTime").value = showFilled(theTime.getHours()) + ":" + showFilled(theTime.getMinutes()) + ":" + showFilled(theTime.getSeconds());
            setTimeout("startClock()",1000);
        }
        function stopClock() {
            clearTimeout("startClock()");
        }
        function showHideClock() {
            if (showHide == "show") {
              document.getElementById("showHide").innerHTML = '<a href="#" onclick="showHideClock()" id="showHide" class="clock">Hide Time</a><br><br><label for="showTime" id="clocklabel" class="clock">Time:</label><input type="text" readonly name="showTime" id="showTime" size="6" class="clock">';
              showHide = "hide";
              startClock();
            } else {
              stopClock();
              document.getElementById("showHide").innerHTML = '<a href="#" onclick="showHideClock()" id="showHide" class="clock">Show Time</a>';
              showHide = "show";
            }
        }
    </script>
    </head>
    <body onLoad="showHideClock()">
      <p id="showHide"></p>
    </body>
    </html>

Credits

Original clock javascript can be found at:
Free javascripts, php and perl scripts