Last week we learned the NAMEs attached to each of the HTML image tags. Today we begin playing around with replacing those image tags with the correct numbers, depending on what time it is.
The time is grabbed from the user’s browser, so there’s no need to worry about daylight savings time or time zones. As long as the viewer has his or her browser set correctly, you’re good to go. If they don’t, well, you can’t help that.
Let’s start at the top of the script just below the loading loop and code:
Don’t get put off by its size. It’s basically the same thing again and again once we get to the numbers.
Now…from the top!
The function is named clock(). You may have noticed it is called for by an onLoad Event Handler in the BODY tag. If you didn’t notice…it is.
See all of the separate elements? Now we need to use some more code to simply suck out the parts we want. In this case we want the hour (getHours()), the Minutes (getMinutes()), and the seconds (getSeconds())
The three items are assigned the variable names "hour", "min", and "sec" respectively.
Now that we have the elements, let's test them.
We'll start with the hour. If it's less than 12, the image tag denoted "amPM" will receive the am.src. If you remember the preload commands, that would be "dgta.gif".
Finally, what if the hour is equal to zero (midnight)? The code says to make "hour" 12. Now that that's all fixed, let's place the hour.
We're worried about two numbers here. If the hour is 10 or better, we need to place a one in the first image and then whatever the hour is in the next. If the hour is 9 or below, we need a blank in the first digit space and whatever the number is below.
It works through a series of "if" statements. We start by asking if the hour is less than 10. If so, then the "tenHour" image tag gets the "dgtbl.gif". That's the blank image. The second image, "Hour", gets the digit equal to the hour (1 through 9). It's done by using the [square brackets] and allowing the variable inside the square brackets to be replaced by the variable value. Make sense?
If the hour is greater than ten, then the first image "tensHour" gets the number one image and the second number is created by the hour minute ten. Remember that the hour return is in military time, but above we took 12 away from any number greater than 12. If the return is 2300 hours, above we took away 12, that takes it to 11, then here we took away ten, that leaves one. One is then used to post the image. Ta da!
The minutes and seconds are also done through some fancy mathematical fun. We'll get to that next week.
Next Week: Minutes and Seconds