Yesterday I posted a simple script describing how you could easily consume an RSS feed on your website. However, just displaying headlines is not so cool. Nein, having the headlines stream in a ticker is much nicer.
Still using Yahoo! News as a source, today we'll discuss how to consume a RSS news feed in a ticker.
The code below does the trick.
<p><b>Yahoo! News: <a id="myTicker" href=""></a></b></p>
We make much use of the window.setTimeout function. setTimeout is used to call another function after a specified time duration. The duration is specified in milliseconds.
The script first loads the RSS feed file into the DOM as the page is loaded. When the body tag's onload event fires we call function GetNewsSource(). This function reads the items node of the RSS file into a nodeList variable and proceeds to extract the title element into variable sText, and the link element into hyperlink myTicker's href property. Once done the script calls function ticker() which writes the content of sText character by character. Function ticker() executes recursively via the setTimeout function with each character being written after 90 milliseconds.
Function GetNewsSource() also executes recursively, and we specifed (90*sText.length +4000) as a setTimeout duration. this ensures that the next execution only kicks off after function ticker() has completed writing the full contents of sText.
To round off the script checks to see if the news headline being written is the last in the feed, and if so resets the feed back to the first item.
And there you go, your own news ticker on your website.