Write Code to Rotate News Items
It's time to write the script that rotates the content. Remember, you've already set up the
<div> container to hold the content in the HTML file. Add the
rotateNews function to your script:
var nIndex = 0;
var timerID = null;
function rotateNews(){
var len = newsArray.length;
if(nIndex >= len)
nIndex = 0;
document.getElementById('stories').innerHTML =
newsArray[nIndex];
nIndex++;
timerID = setTimeout('rotateNews()',6000);
}
As you can see, there isn't anything really special going on here. The
nIndex counter variable keeps track of which news item to display. When it gets to the end of the array, the code resets the counter to zero so that the process can start overthus "rotating" the items in the array. The call to
setTimeout keeps the function chugging along. Then, the code assigns the contents of one of the members of the array to the
innerHTML property to the stories
<div>. You may have noticed that a variable called
timerID holds the value of the timer ID created by the call to
setTimeout. You'll use that variable to start and stop the rotation based on whether the user moves the mouse over the content area. That's because it's terribly frustrating to users to mouse over a link and then have it change before they can click the link. To make the display pause and re-start the rotation, add the following code to the script file:
function pauseNews() {
if (timerID != null) {
clearTimeout(timerID);
timerID = null;
}
}
function playNews() {
if (timerID == null) {
timerID = setTimeout('rotateNews()', 1000);
}
}
Save the file as
rotate.js in the same folder as the HTML file.