Home

Help

Search


Introduction to Java Script - A clock

Developed by Netscape, JavaScript is a compact, object-based scripting language for developing client-side interactive Web pages. In this month's HTML project Helen Bradley introduces you to JavaScript by showing you how to create a simple clock on a Web page. This source will work with Netscape Navigator 3 and above or Internet Explorer 4.

 

What makes JavaScript special
JavaScript now has the support of both Netscape and Microsoft. It's a reasonably simple language to learn and you can create some useful programs using it. It's available to anyone with one of the current-version browsers, and one advantage it has is that you don't require anything extra to write JavaScript. The programming code is not compiled but is interpreted in real time from within your HTML document, so all you need is a way of editing HTML source, and a sense of adventure.

The downside of this is that your code is exposed for anyone to see and use, so it is difficult to protect your programs if you have expended a great deal of time and effort in creating them. You can either accept this disadvantage and continue to use JavaScript or rewrite your code using Java or a server-side program.

As well as creating killer Web sites, JavaScript is a great way to get your feet wet with programming. There are many sites that provide great JavaScript samples and tutorials (see below) so there is plenty of resource material around that you can use and adapt. It also complements other languages such as the more powerful, though more opaque, Java language, for example.

If you have program experience you will notice that because you add your code into a simple .htm file you will not have the context-sensitive help that is available in other programming languages. The JavaScript interpreter in your browser will alert you if there is a syntax error in your program, but it won't pick up any mistakes in the associated HTML. In general, you'll find there's less onscreen help, checking and support than you are used to.

 

Creating your JavaScript clock
To create the JavaScript clock type the source from the HTML Source box in an HTML editor or text editor such as Windows Write, and save it as an .htm file. Load it into your browser using File, Open and watch the clock appear on the screen and update every 10 seconds.

 

FIG1As.gif (13792 bytes)
This month we introduce the JavaScript language and use it to produce a simple clock.

 

 

FIG1Bs.gif (12849 bytes)

 

 

FIG1Cs.gif (6663 bytes)

 

 

FIG1Ds.gif (4509 bytes)
avaScript code is interpreted from within your HTML document so, to create it, all you need is a way of editing HTML source such as HotDog Pro.

 

 

note.gif (244 bytes)JavaScript Babble - It's really not that Bad.

 

 

note.gif (244 bytes)HTML Source box

How it works
JavaScript is contained in an HTML document inside a pair of ltSCRIPTgt...lt/SCRIPTgt tags. This tag pair indicates that there is script embedded in the document, and indicates which language has been used, so that the browser knows how to interpret the script. Placing the SCRIPT tags in the HEAD of a document and surrounding the actual script with a set of HTML comment tags lt!-- .. --gt, means that it will be ignored by browsers that do not support JavaScript, and your viewer won't see lines of programming code on the screen.

However you may need to filter browsers that provide incomplete support such as Internet Explorer 3's JScript (which is a close but occasionally incompatible variant of JavaScript 1.0). To be certain about which browsers can and can't view your script, test it on Netscape 3, 4 and IE 3 and 4. In a later column we'll show you a JavaScript routine to filter browsers which do not support the script and we will also show you how to handle the display for each differently.

Each of the lines within the script which are prefixed by two slashes (//) are comments and are ignored when the script is run. Using comments makes it easier to read the script and to troubleshoot it if something goes wrong. Adding comments liberally throughout your document is a skill worthwhile developing.

The data for the clock is produced by the function setTime(). This function is run when the HTML page is fully loaded by the OnLoad event handler which is set in the ltBODYgt tag with this code:

ltBODY OnLoad = "setTime()"gt

When the form is loaded the OnLoad event handler calls the function setTime.

This function creates a new instance of the date object, which has been called currentTime and contains information about the current date and time. Once this date object has been created you can use any of the date methods to extract date information from it. The methods used here are getHours which gets the hour of the day from the date object where it is stored based on a 24 hour clock (0-23 hours). The line currentHours = currentTime.getHours() assigns the current hour to the variable currentHours. The getMinutes method gets the current minute (in the range 0 - 59) and here the result is stored in the variable currentMinutes.

The rest of the function takes the data from the two variables currentHours and currentMinutes and formats it from a 24 hour clock to a 12 hour clock. It also keeps track of the time of day in the variable currentAmPm. To convert from a 24 hour clock to a 12 hour clock, four checks are made on the data in the variable currentHours. First a check is made to see if the hours are greater than 12:

if (currentHours) gt 12)

If they are then they're reduced to the range 0-12 by deducting 12 from them. Thus 13 hours becomes 1 (13-12) and 23 hours becomes 11 (23-12) and so on.

The second check is made on only those hours that were not greater than 12 and tests whether the hours are less than or equal to 11:

if (currentHours lt= 11)

If the number of hours is less than 11 (ie. in the range 0-11) then it is morning. Because the variable currentAmPm was initialised earlier in the program with 'pm' it need only be altered if it is morning and this is done with the statement:

currentAmPm = 'am'

The third test is to see if the hours are equal to zero because this is really midnight:

if (currentHours == 0)

Because of the nesting of the `if` statements, this test is only made in the case of the hours being not greater than 12. If the hours are zero then they need to be set to 12 so 12 is added to the currentHours. You'll see that the test for equality is two equal signs side by side which is different to the way most programming languages test for equality.

The final test is done in all instances and tests to see if the new value of currentHours is less than or equal to 9:

if (currentHours lt= 9)

In this case a space is added before the number of hours to 'pad out' the hours so that the time display does not sit hard against the left-edge of the text box in the final display.

The logic of these tests is:

if the hours are more than 12 then adjust them to display in the range 0 - 11
or else
    if they are less than or equal to 11  make the time of day "am"
    and if the hours are equal to zero make the hours equal to 12
if the hours are now less than or equal to 9  pad them out to two digits

The final 'if' test deals with the situation of the minutes being in the range 0-9 and adjusts them to two digits by adding a zero in front of the number:

if currentMinutes lt= 0

Finally the hours and minutes are assembled together into a string which will be displayed in the text box in a form on the screen. A colon is added between the hours and the minutes and the time of day is included at the end of the string. Thus the string will be in the format: 12:35am.

The last line of the script uses the JavaScript setTimeout function which operates the timer. The delay here is 10,000 milliseconds (or 10 seconds) and, after that time has elapsed the function setTime is called again. This has the effect of the function repeatedly calling itself so that every 10 seconds the entire process of reading the system clock, adjusting the data, and creating a string for display takes place.

The HTML source provides a place for displaying the time string. In this case a form has been created (called displayClock) with one text box (called time) in which the string is displayed with the line from the setTime function itself:

document.displayClock.time.value = currentTime

This displays the value in the variable currentTime in the text box called time in the form called displayClock on the current page.

 

Customise it
This basic clock can be customised in a number of ways using other date and time methods. For example you can add seconds to it using the getSeconds method which returns the number of seconds in the range 0 - 59.

You can also display the current date using these functions:

getDay    returns a number 0 - 6 representing a day of the week (0 = Sunday, 1 = Monday.. 6 = Saturday)
getDate    returns the number of the day of the month in the range 1 - 31
getMonth    returns the number of the month in the range 0 - 11, so that January = 0, February = 1.. December = 11. You will need to adjust this by adding one to it to display the actual month number.
getYear    returns a two digit year number.

You can also alter the timer delay by altering the line that controls this:

setTimeout("setTime()",10000)

By increasing the number of milliseconds you can have the clock update less often or decrease the number to have it update more often.

If you add extra information to your time string you'll need to increase the size of the text box in the form that displays the string. This line controls the text box:

ltINPUT TYPE = "text" NAME = "time" SIZE= 8>

Alter the size to increase the number of characters that the text box will display.

 

Files on CD
jsclock.htm contains the source for the JavaScript clock with minor adjustment of fonts to improve the display. If you have problems viewing it with your current browser, try installing either Netscape Navigator 4 or Internet Explorer 4 from the cover disc and view it using one of these browsers.

Note: This javaScript example will not function properly if you are using our default on-CD browser. You need to be using an installed version of Internet Explorer or Netscape Navigator/Communicator.

 

By Helen Bradley and John Hilvert

 


Top of page

|What's New | Net Guides | Web Workshop | Net Sites | About PC User |
| Games | Education | General & Business | Online Tools | Utilities |
| Patches & Support files | PC User Interactive |

All text © 1997 Australian Consolidated Press - PC User Magazine