Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: A Better Scrolling Message

In Hour 5 , "Using Strings and Arrays," you created a script that scrolls a message across the browser's status line. Using the DOM objects, you can create a better scrolling message—one that scrolls within the Web page itself.

To do this, you can start with the scrolling message example from Hour 5. Instead of assigning the message to the window.status variable, you can display it in a text node within the page. Listing 20.4 shows the complete HTML document for this example.

Example 20.4. The New Scrolling Message Example

<html>
<head>
<title>Scrolling Message Example</title>
<script language="JavaScript" type="text/javascript">
msg = "This is an example of a scrolling message ";
msg += "that appears in the body of the page. ";
msg = "......." + msg;
pos = 0;
function ScrollMessage() {
   var newtext = msg.substring(pos, msg.length) + msg.substring(0, pos);
   var td = document.getElementById("scroll");
   td.firstChild.nodeValue = newtext;
   pos++;
   if (pos > msg.length) pos = 0;
   window.setTimeout("ScrollMessage()",150);
}
</script>
</head>
<body onLoad="ScrollMessage()">
<h1>A Better Scrolling Message</h1>
<p>Rather than using the status line, this page uses
the DOM to scroll a message within the small table below.</p>
<table width="90%" border>
<tr>
<td ID="scroll" width="90%"> The scrolling message goes here.</td>
</tr>
</table>
</body>

In this example, the <table> section defines a simple table to contain the scrolling message. The <td> tag has an identifier of scroll, and will be the actual container for the scrolling text.

The <script> section in the header initializes the variables for this script, and the ScrollMessage function performs the actual scrolling. This function is first called by the document's onLoad method.

The first two lines of the ScrollMessage function scroll the message within the newtext string. Next, the function assigns the td variable to the table cell where the scrolling will happen using getElementById, and sets the cell's text node value to the new version of the message.

Finally, the pos counter is updated for the current scroll position, and the setTimeout method is used to call the ScrollMessage function again after a short delay. Figure 20.4 shows this example in action in Netscape 6.

20fig04.jpg

Figure 20.4 The new scrolling message, as displayed by Netscape 6.

Share ThisShare This

Informit Network