Categories:

Adding a live clock with the help of a form

Adding a live clock using forms is quite simple. The basic concept is to continuously write to a form field every 1 second, using the updated time from your own computer. Last section, we already discussed the essence of how to achieve calling a function continuously (by using the setTimeout function in a special manner) -now all we need to do is use that knowledge. First, lets see the date object again and some of its methods:

Some methods for the date object:
getDate()   returns the day of the month
getDay()   Returns the day of the week
getHours()   returns the hour (Starts from 0-23)!
getMinutes()   returns the minutes
getSeconds()   returns the seconds
getMonth()   returns the month. (Starts from 0-11)!
getFullYear()   returns the year
getTime()   returns the complete time (in really weird format)

You may want to cut and paste the below code and play around with it:

<form name="Tick">
<input type="text" size="12" name="Clock">
</form>

<script type="text/javascript">
function show(){
	var Digital=new Date()
	var hours=Digital.getHours()
	var minutes=Digital.getMinutes()
	var seconds=Digital.getSeconds()
	var dn="AM" 
	if (hours>12){
		dn="PM"
		hours=hours-12
		//this is so the hours written out is in 12-hour format, instead of the default //24-hour format.
	}
	if (hours==0)
		hours=12
	//this is so the hours written out when hours=0 (meaning 12a.m) is 12
	if (minutes<=9)
		minutes="0"+minutes
	if (seconds<=9)
		seconds="0"+seconds
	document.Tick.Clock.value=
	hours+":"+minutes+":"+seconds+" "+dn
	setTimeout("show()",1000)
}
	show()
</script>
  • Believe it or not, that's all there really is to it!
  • Look at line 11. We first set "dn=AM". If the hours is > 12, meaning its afternoon, we set "dn=PM". If minutes/seconds is greater than 9, we added a "0" to it...why? because we want to pad it, just to make it look better. That's the basic structure of function show()
  • The most important part, the setTimeout method, was already discussed prior to this page. Basically, this script is run every one second, which gives the illusion that the clock is actually ticking.
  • Remember, the format of hours in JavaScript is from 0~23, not 1~24! That's the reason why we set it to display "12" whenever hours=0.

You, by no means, have to use a form when implementing your clock, but a form has many advantages: it is easy to add to your code, and more importantly, since all it does it "write" to a form, there is virtually no delay in time every second as it writes a new value to the text form. It is possible to implement a live clock that uses images. For an example of such, click here.