JavaScript : Create Dynamic Content
Contents ]
Claude Levior

Pages Which Change Over Time

What is the benefit of automatic text generation with JavaScript? Flexibility - and we will be making use of the if instruction to illustrate that. This instruction allows you to set conditional tests to control the script execution flow.

The following program writes Good morning, Good afternoon or Good evening, depending on the time at which the visitor consults the page:

1: <SCRIPT>
2:   Now = new Date();
3:   if (Now.getHours()>17)
4:   {
5:     document.write('<B>Good evening</B>');
6:   }
7:   else if (Now.getHours()>12)
8:   {
9:     document.write('<B>Good afternoon</B>');
10:   }
11:   else
12:   {
13:     document.write('<B>Good morning</B>');
14:   }
15: </SCRIPT>

Be careful about the numbers. Pay particular attention to the line numbering which has only been added to simplify descriptions. The scripts will not work if you keep these numbers.

Spot the difference?! The text which shows up now depends on the time at which it is displayed..

How does all this work?

The variable Now of the type Date is created in line 2.

In lines 3 to 13, a conditional expression if helps to determine the message to be displayed depending on the time of the visit. The function getHours applied to the variable Now returns the current time (from the system clock of the visitor's computer connected to the site). We check whether it is greater than the value 17. If so (i.e. the condition in line 3 evaluates as true), the instruction in line 5 between the first pair of brackets is executed.

If the condition is false, another conditional expression (else if) checks if the time is greater than 12. If so, the instruction in line 9 is executed.

And if the second condition is also false, the instruction in line 13 of the else group of brackets is executed.

Needless to say, this principle can be applied to other types of criteria in the same way, e.g. user's browser version, visitor's country, user's operating system. Generally, a condition can be based on any variable information which JavaScript can return.

Moreover, as you will see very soon in other workshops, the content of a page can be automatically modified subsequent to any kind of event: click or movement of the mouse, connection to another page, document refresh, etc.

To be continued ...