Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Workshop: Displaying a Scrolling Message

One of the most common uses of JavaScript is to create a scrolling message in the browser's status line. You can create a scrolling message using the string methods you have learned in this hour.

To begin, you'll need to define the message to be scrolled. You will use a variable called msg to store the message. To begin the script, initialize the variable (feel free to choose your own text for the message):

msg = "This is an example of a scrolling message. Isn't it exciting?";

Next, add a spacer string to the beginning of msg. This will be displayed between the copies of the message to make it clear where one ends and the other begins. This statement adds the spacer to msg:

msg = "...     ..." + msg;

You'll need one more variable: a numeric variable to store the current position of the string. Call it pos and initialize it with 0:

pos = 0;

The actual scrolling will be done by a function called ScrollMessage. Here is the JavaScript code for this function:

function ScrollMessage() {
   window.status = msg.substring(pos, msg.length) + msg.substring(0, pos);
   pos++;
   if (pos > msg.length) pos = 0;
   window.setTimeout("ScrollMessage()",200);
}

The ScrollMessage function includes the following commands:

To complete the example, add the <script> tags and the HTML tags that make up a Web document. Listing 5.2 shows the complete scrolling message example.

Example 5.2. The complete 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. Isn't it exciting?";
msg = "...          ..." + msg;pos = 0;
function ScrollMessage() {
   window.status = msg.substring(pos, msg.length) + msg.substring(0, pos);
   pos++;
   if (pos > msg.length) pos = 0;
   window.setTimeout("ScrollMessage()",200);
}
ScrollMessage();
</script>
</head>
<body>
<h1>Scrolling Message Example</h1>
Look at the status line at the bottom of this page. (Don't
watch it too long, as it may be hypnotic.)
</body>
</html>

Figure 5.2 shows the output of the scrolling message program.

05fig02.jpg

Figure 5.2 The scrolling message example in action.

Share ThisShare This

Informit Network