Rotate Content Easily with Object-Oriented JavaScript

Presenting information on the web can be a challenge, especially when you need to show more information than fits neatly on a given screen. This article presents a way to increase the density of information on the screen by rotating content within a fixed area dynamically. The popularity of rotating content areas indicates that users appreciate the value of having content on the page change dynamically. The trick is to change the content in such a way as not to distract the user. You can do that by limiting the area that changes, thus allowing users to view your content while simultaneously giving you a way to present more of the information that users crave.

Many Web sites possess an abundance of information?but screen real estate is at a premium. One method for presenting a lot of information in a small space is to create an area that rotates content within your page. So, the problem is, how do you create a rotating content area?

Write some simple object-oriented JavaScript, and a few style rules, combine them with a timer and some common-sense UI design guidelines, and you’re well on your way!

Create an HTML Page to Hold Rotating Content
To begin, you need an HTML page where you can experiment with rotating content. You can use the following simple page use the following code as a base HTML page for the sample project described in this solution. Open your favorite text editor and enter the following code.

      News Rotator            
Today's News

The code used in this solution creates a news application, but the metaphor works equally well for any type of information your application requires. The only notable code in the HTML file is the

tag that holds a list of news stories?that’s where you’ll write the rotating content dynamically. Save the file as news.htm.

Create JavaScript News Items
Open a second file in your text editor to hold the JavaScript portion of the application. Following object-oriented principles, you’ll create a class that has properties appropriate for a news item. Add the following constructor to create a news item:

   function makeNews(c,l,f,i){      this.copy = c; = l;      this.follow = f;      this.img = i;      this.write = writeNews;   }

You call the makeNews method to create news objects. Each object takes four parameters: the copy (c), the link (l), the follow text (i.e. what to display as the link) (f), and an image (i). News objects also need a method to writing their content to the page. I’ve called that method write, and associated it with the writeNews function. Add the following writeNews function to your script:

   function writeNews(){      var str = '';      str += '';      str += '
'; str += this.copy + '
'; str += '' + this.follow + ''; return str; }

As you can see, writeNews simply translates the properties of each news item into an HTML string. The string shown in the preceding code is arbitrary; you can modify the writeNews function to suit your needs as long as it writes well-formed HTML.

Because I wanted to be able to include an accompanying image in each news item’s display, I’ll provide image objects to force the browser to pre-load the images. It’s always a good idea to pre-load your images?especially if they aren’t visible when the page loads. Add the following code to pre-load the images:

   var listImg = new Image();   listImg.src = 'watch.gif';   var treeImg = new Image();   treeImg.src = 'dhtml.gif';   var formImg = new Image();   formImg.src = 'form.gif';   var autoImg = new Image();   autoImg.src = 'web.gif';

Next, you need a collection of the news items to display on the page. I’ve used an array for the collection. Add the following to your script (each statement should be on a single line):

   var newsArray = new Array();   newsArray[0] = new makeNews(      "Move Items Between Lists With JavaScript",       '',       'Read More',listImg).write();      newsArray[1] = new makeNews(      "Build an XML-Based Tree Control With JavaScript",      '',      'More Info',treeImg).write();      newsArray[2] = new makeNews(      "Automate Your Form Validation",      '',      'Full Story',autoImg).write();      newsArray[3] = new makeNews(      "Create Fast, Smooth Multi-Page Forms With JavaScript",      '',      'More Info',formImg).write();

Note that you’re not really interested in storing the news objects themselves in the array; instead, you want the array to contain the results of the call to each news object’s write method. The preceding code stores the HTML string for each object in the array. That occurs because the new operator takes precedence over the call to the write method. In essence, the code first creates each news object, is created, and then calls its write method. The result is that the array stores the string returned from the call to each news object’s write method rather than the news objects themselves. Also note that I’ve passed in a reference to the pre-loaded image object for each item.

Write Code to Rotate News Items
It’s time to write the script that rotates the content. Remember, you’ve already set up the

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 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

. 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.

Make It All Work
There are three tasks remaining. First, you need to include the script file you just created in the HTML file you created at the beginning of this solution. Add a reference to the script file in the section of the HTML document:


Next, you want to start the news items rotating when the page loads. To do that, attach a call to rotateNews to the onLoad event of the element:


Finally, you want to make the

container stop rotating when the user’s cursor enters the container, and begin rotating again when the cursor leaves. To do that, attach mouseOver events to the news



Test your code by loading the HTML file into your browser. You’ll see the items rotate each time the timer fires. You can see that this approach lets you increase the amount of content available to your users and simultaneously adds visual appeal to the page. You can see a modified version of this script (I left out the images) at That site needed a way to present new news items effectively and this script fit the bill nicely. This script has been tested in and works with IE6, Mozilla 1.4, and Opera 7.11.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Related Posts