Rotate Content Easily with Object-Oriented JavaScript

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;      this.link = 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",       'http://www.devx.com/GetHelpOn/10MinuteSolution/16372',       'Read More',listImg).write();      newsArray[1] = new makeNews(      "Build an XML-Based Tree Control With JavaScript",      'http://www.devx.com/getHelpOn/Article/11874',      'More Info',treeImg).write();      newsArray[2] = new makeNews(      "Automate Your Form Validation",      'http://www.devx.com/gethelpon/10MinuteSolution/16474',      'Full Story',autoImg).write();      newsArray[3] = new makeNews(      "Create Fast, Smooth Multi-Page Forms With JavaScript",      'http://www.devx.com/webdev/Article/10483',      '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

container:

   

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 http://www.ncc.commnet.edu. 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.

devx-admin

devx-admin

Share the Post:
Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI,

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new

Game Changer

How ChatGPT is Changing the Game

The AI-powered tool ChatGPT has taken the computing world by storm, receiving high praise from experts like Brex design lead, Pietro Schirano. Developed by OpenAI, ChatGPT is known for its

Web App Security

Web Application Supply Chain Security

Today’s web applications depend on a wide array of third-party components and open-source tools to function effectively. This reliance on external resources poses significant security risks, as malicious actors can

Thrilling Battle

Thrilling Battle: Germany Versus Huawei

The German interior ministry has put forward suggestions that would oblige telecommunications operators to decrease their reliance on equipment manufactured by Chinese firms Huawei and ZTE. This development comes after

iPhone 15 Unveiling

The iPhone 15’s Secrets and Surprises

As we dive into the most frequently asked questions and intriguing features, let us reiterate that the iPhone 15 brings substantial advancements in technology and design compared to its predecessors.

Chip Overcoming

iPhone 15 Pro Max: Overcoming Chip Setbacks

Apple recently faced a significant challenge in the development of a key component for its latest iPhone series, the iPhone 15 Pro Max, which was unveiled just a week ago.

Performance Camera

iPhone 15: Performance, Camera, Battery

Apple’s highly anticipated iPhone 15 has finally hit the market, sending ripples of excitement across the tech industry. For those considering upgrading to this new model, three essential features come

Battery Breakthrough

Electric Vehicle Battery Breakthrough

The prices of lithium-ion batteries have seen a considerable reduction, with the cost per kilowatt-hour dipping under $100 for the first occasion in two years, as reported by energy analytics

Economy Act Soars

Virginia’s Clean Economy Act Soars Ahead

Virginia has made significant strides towards achieving its short-term carbon-free objectives as outlined in the Clean Economy Act of 2020. Currently, about 44,000 megawatts (MW) of wind, solar, and energy

Renewable Storage Innovation

Innovative Energy Storage Solutions

The Department of Energy recently revealed a significant investment of $325 million in advanced battery technologies to store excess renewable energy produced by solar and wind sources. This funding will

Renesas Tech Revolution

Revolutionizing India’s Tech Sector with Renesas

Tushar Sharma, a semiconductor engineer at Renesas Electronics, met with Indian Prime Minister Narendra Modi to discuss the company’s support for India’s “Make in India” initiative. This initiative focuses on

Development Project

Thrilling East Windsor Mixed-Use Development

Real estate developer James Cormier, in collaboration with a partnership, has purchased 137 acres of land in Connecticut for $1.15 million with the intention of constructing residential and commercial buildings.

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing