Learn Scripting Languages from the Master!
This example will show you to build digital clock in JavaScript. To create the clock, we will use three JavaScript methods: getHours () to get the hour, getMinutes () to get minutes, and getSeconds () to get seconds. See the code below for details.
The following shows the output of the script code shown below:
Step 1: place the following JavaScript code in the head section (between <head> and </head>) of your web document.
<script language="javascript">function DisplayTime () {dateObj = new Date();var hour = dateObj.getHours();var minutes = dateObj.getMinutes();var seconds = dateObj.getSeconds();if (hour < 10) {hour = "0" + hour;} if (minutes < 10) { minutes = "0" + minutes; } if (seconds < 10) { seconds = "0" + seconds; } document.clock.time.value = hour + ":" + minutes + ":" + seconds; setTimeout("DisplayTime()", 1000); } </script>
Step 1.1: place also the following styling code before <script> tag or after </script> tag, if any, but in the head section (between <head> and </head>) of your web document.
/* defining styles for our clock through a class called TimeBox */.TimeBox {border:#0083C1 1px solid; /* border color, size, and type */font-size:10pt; /* font size to use*/background-color:#0083C1; /* background color of the time/input box */color:#FFFFFF; /* font color*/font-family:"Courier New", Courier, monospace; /* type of font*/text-align:center; /* align our time to the center*/font-weight:bold; /* display time bold-type */}Step 2: Place the following code in your web page:
<form name="clock"><table width="80" border="0" cellspacing="0" cellpadding="2"><tr align="center"><td><input type="text" name="time" size="8" class="TimeBox" /><script language="javascript">DisplayTime ();</script></td></tr></table></form>