|

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.
Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS
-Free applets
-Web Tutorials
-Link to Us!
|
 |
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 the form 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. You may want to cut and paste the below code
and play around with it:
//clock
<form name="Tick">
<input type="text" size="12" name="Clock">
</form>
<script>
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 the part in blue. 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.
-Tutorial introduction
-The date object
-Dynamically writing out html codes
-The setTimeout function
-Adding a live clock with the help of a form
-Example: To watermark or not to watermark?
Example: To watermark or not
to wartermark?  |