How to implement the JavaScript clock?This is what the JavaScript clock looks like:
This is what the JavaScipt looks like for the JavaScript clock. Place the following code in the head of your html page:
<script type="text/javascript">
function updateclock() {
//Get the current time
var time = new Date();
var todisplay = '';
//Add a 0 infront of the hour, minute or second if it is less than 10
if (time.getHours() < 10) todisplay += '0' + time.getHours();
else todisplay += time.getHours();
if (time.getMinutes() < 10) todisplay += ':0' + time.getMinutes();
else todisplay += ':' + time.getMinutes();
if (time.getSeconds() < 10) todisplay += ':0' + time.getSeconds();
else todisplay += ':' + time.getSeconds();
//Refresh the display
document.getElementById("clock").innerHTML = todisplay;
}
function startclock() {
//Initial call otherwise the clock would display blank for the first second
updateclock();
//Update the clock every second, i.e. every 1000 milliseconds
setInterval("updateclock()",1000);
}
</script>
Place a container for the JavaScript clock on the page and start the clock using inline JavaScript. The container can be a textbox, div, span, basically anything. Make sure to then change the line document.getElementById("clock").innerHTML accordingly:
<span id="clock"> <script type="text/javascript">startclock();</script> </span>
|
Where was the JavaScript clock tested?The JavaScript clock was successfully tested under Internet Explorer 6, Internet Explorer 7, as well as Firefox Version 2.0.0.14. |