First, we'll define the function "createNewsDiv()", which will simply create the containing <div> element for displaying news in sequence. Its definition is as follows:
// create news containing <div> element
// insert news <div> into document structure
As you can see, the above function is easy to understand. It simply creates a <div> element, then assigns to it an ID attribute "news", handy for tying a style to the element. Finally, the function inserts it into the Web document tree. Notice that I've opted to append the news <div> as a new child element of the body, using the line:
However, this might be quickly changed to set a different insertion point. Let's suppose we want to hang the news <div> element inside another container <div>. If we do so, the above expression would be replaced with the following line:
That's not rocket science, right? Now that we've created the news container, let's have a look at the next function, "rotateNews()", which as its name implies, displays in sequence our headlines at a specified time interval. Here's the function code:
Our next step is to manipulate the document structure and generate the HTML elements that hold each headline. Thus, first we grasp the news <div> containing element for further replacement. Second, we create a <div> element in memory, and assign to it an ID attribute. This element will be the generic container for our news ticker, as we'll see in a moment. Next, we need to create an HTML element to place every headline in the document.
For this purpose, I've decided to create a paragraph and apply a style it, specifying a font type, font size, and color, respectively. Therefore each one of the headlines will be rendered inside a <p> element. Still with me, right? Okay, now let's check out the function's workhorse.
As you can see, the "counter" variable behaves as a headlines pointer, to display the information in the correct sequence. Once our headline is inserted into the Web page, what else can we do? Not much, really. The only thing left is to display the headline content, increment the counter, and make the whole process happen each N milliseconds, in the following way:
// insert paragraph into <div> news
// replace old <div> node with new <div> node
// rotate news every 10 seconds