
This tutorial is aimed at those of you who are new to javascript, but already have a little bit of understanding in areas such as variables, and events.
The clock that you will build in this simple JavaScript tutorial, uses a number of arrays and variables, along with an HTML text box component in which the date and time are displayed. The tutorial will also show you how to use the html documents body 'onload' and 'onunload' events to trigger global functions, and we will also be using the javascript 'setTimeOut' function which causes the page to refresh itself at intervals we specify.
Lets get started shall we?
The first thing we need to do is to setup the variables, arrays and functions that we will use. To make sure that script anywhere in the document can access these things, they need to be made global, i.e. defined in a script in the documents '<Head>' section.
For this clock, we will need the following variables and arrays outlined below. Please note that because this is only a simple JavaScript lesson, I am placing emphasis on the way variables and arrays work so this code is not 100% efficient and it could be written with a lot less code. Variables and Arrays we will need:
As well as all these variables and arrays, we will need two functions for the clock to work. One to start the clock, and one to stop the clock. These two functions will be triggered when the Page Loads, and Unloads respectively.
Now we know what we need, we can define them in our document. Start a new HTML document and add the following code into the documents '<Head>' section.
<SCRIPT LANGUAGE = "JavaScript">
var time_me = null;
function stop()
{
clearTimeout(time_me);
}
function start()
{
var days = new Array;
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saterday";
var months = new Array;
months[0] = "January";
months[1] = "Febuary";
months[2] = "March";
months[3] = "April";
months[4] = "May";
months[5] = "June";
months[6] = "July";
months[7] = "August";
months[8] = "September";
months[9] = "October";
months[10] = "November";
months[11] = "December";
var sysTime = new Date();
var hours = sysTime.getHours();
var minutes = sysTime.getMinutes();
var seconds = sysTime.getSeconds();
var dayNumb = sysTime.getDate();
var theMonth = months[sysTime.getMonth()];
var theDay = days[sysTime.getDay()];
var clock =((hours<10)? "0" : "")+ hours;
clock+=((minutes<10)?":0" : ":")+ minutes;
clock+=((seconds<10)?":0" : ":")+ seconds;
document.forms[0].display.value = theDay + " " + dayNumb + " " + theMonth
+ " " + clock;
time_me = setTimeout("start()",1000);
}
</SCRIPT>
The way this script works is quite straight forward. First of all, it declares a global variable and initialises it so that is it empty. This variable is used later on to hold the result of setting the pages timeout property.
The next thing we do is to create a new function called Stop(). This function is called when the page is closed and it is used to do one thing, and that is to erase the pages timeout from memory. This is just a clean up function.
Next up is the start function which at first glance, can look quite daunting to a beginner. There is a lot going on inside this function but it is all easy enough to understand.
The first thing the start function does is to setup two arrays, one to define the names of the days of the week, (using sunday as the first day), and and to define the months of the year. Notice how the elements of the array start at 0, and not 1. This is because Arrays elements start at element zero and work up. Arrays will be detailed in another tutorial and we will not look at them much here. All you need to know is that an array is a collection of variables that are the same type. You access them by calling the name of the array, and specifying the number of the element you wish to retrieve. For example, if I wanted to access the 5th element from the days array, I would call 'days[4];', and this would return Thursday.
After these arrays have been setup and defined, we then create an instance of a 'Date()' object. When you create a date object as we have here, with no parameters in its constructor, the new Date instance will hold the systems date and time from when it was created. It should be noted that our sysTime variable is not actually a variable, it is in actuality an Object. Again, variables and objects will be discussed in another tutorial. All you need to know is that Objects have functions that can be called upon, which will become apparent in the next part.
After our sysTime Date Object has been initialized, we then setup 6 variables to hold certain parts of the date and time. They are named accordingly and each one gets its value from calling a function from the sysTime Date object. for example, var hours = sysTime.getHours(); will create a new variable called hours, and its initiation value is the value that is returned by the 'getHours();' function of the sysTime object.
The next few lines do nothing more than construct a new String variable and take the values from our variables and create a date and time string to display on the page. In the case of the Day and the Month, the code looks up the appropriate name to display for each using the retrieved day and month number, and displays the values in the related array element instead.
The second to last thing the Start() function does is to display the contents of the new string in a text box on the web page called 'display'. We will add this to the page in step two.
Last but not least, the function sets up a trigger that will call the Start() function again, in 1 seconds time. Using this method, we have essentially created an infinite loop. This function will execute itself once every second from the time it is started, to the time the stop function is called when the page unloads.
You really need to read this code and work out what does what. I have given you the basics and theory of how it works, but it is up to you to decipher the code and really understand it. It is all very straight forward and should not pose too much of a problem.
The next thing we need to do is a lot easier than Step 1. We just need to create a new form, with a single text field called 'Display'. Copy the code below into the 'Body' section of your document.
<form>
<input type="text" name="display" size="30">
</form>
As you can see, this just creates a simple text field on the page. Nothing (hopefully) new there or complicated. Onto Step 3.
This is the last and final step for the tutorial. All we need to do is to tell the page to trigger the Start() function when it loads, and to trigger the Stop() function when the user closes the page. This is accomplished, quite easily, by changing the '<body>' tag of your HTML document to match the following line of code:
<body onload="Start();" onunload="Stop();">
Now that we have finished our coding, its time to test the script. Save the page and load it up in your browser, and you should see something like the following:
And there we have our clock.
Tutorial by Justin Kercher
2005.
This document may not be copied for use on another site.
Copyright© 2005.