RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Rotate Content Easily with Object-Oriented JavaScript-4 : Page 4

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 = 
      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 over—thus "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) {
         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.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date