Rotating Text Banners: Rotating the Messages - Doc JavaScript | WebReference

Rotating Text Banners: Rotating the Messages - Doc JavaScript

Rotating the Messages

We need to put everything together to get the banner spinning. First, let's set the onload event handler to start the banner:

onload = start;

Since onload is a property of the window object, you can omit the object specification. window is the default object. The start() function obviously starts the banner:

function start() {
  setInterval("update()", 2000);

Notice that we are not assigning the returned value of setInterval() to a variable, so it is not possible to stop the banner. We use setInterval() to invoke our update() function every 2000 milliseconds (2 seconds).

In general, the setInterval() function repeatedly calls a function or evaluates an expression after a specified number of milliseconds has elapsed. The timeouts continue to fire until the associated window or frame is destroyed, or the interval is canceled using the clearInterval() method. Its cross-browser syntax is as follows:

var varName = setInterval("statement", msec);

Notice that the banner starts running only when the page has fully loaded, because the first function call is initiated by the onload event handler. If this concerns you, simply delete the onload specification and put the following script anywhere in the document, after the <SPAN>...<SPAN> definition:

<SCRIPT LANGUAGE="JavaScript1.2">
// -->

As you can see, the update() function advances the banner, and resets the counter if it has reached the last element of the array:

function update() {
  display("banner", ar[num]);
  if (num == ar.length) num = 0;

The array ar simply holds the banner's messages:

var ar = new Array();
ar[0] = "<STRONG>Hot sites:</STRONG> <A HREF='/js/'> -->
Doc JavaScript</A>";
ar[1] = "<STRONG>Hot sites:</STRONG> <A HREF='/dhtml/'> -->
Dynamic HTML Lab</A>";
ar[2] = "<STRONG>Hot sites:</STRONG> <A HREF='/3d/'> -->
3D Animation Workshop</A>";

We initialize num to 0 so the banner starts on the first message:

var num = 0;

Created: September 25, 1997
Revised: April 16, 1998