Introduction To Javascript
Message Script

The following code is for a web page with a text box. Messages are set to appear in the box at set intervals. In line 14, the onload event handler calls the function to change the message as soon as the page loads. Line 4 defines the messages. Lines 6 and 7 decide which message to show next and line 8 changes the value of the text box to the new message. Line 9 sets the function to run again every second.

<script type="text/javascript">
var compliments = new Array('You are great!','You look fantastic!', 'Wow, you are brilliant!', 'I wish I was as cool as you')
function chang() {
var e = compliments.length - 1
var x = Math.round(Math.random()*e)
document.myForm.myBox.value = compliments[x]
var s = setTimeout("chang()",1000)
<body onload="chang()">
<form name="myForm">
<input type="text" name="myBox" size="50">

Exercise 15

Copy and adapt the code above to make a newsticker for a web page. Instead of using random numbers work out a way to cycle through the messages one at a time, starting again at the beginning when all of the messages have been displayed.