Discusses how to implement a javascript news ticker which is feed via RSS.

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.

<html>
<head>
<script type="text/javascript">
var sText = ""
var i=0
var iNews=0
var rss = new ActiveXObject("Microsoft.XMLDOM")
rss.async = false
rss.load("http://rss.news.yahoo.com/rss/world")

function GetNewsSource(){
var itemNodes = rss.selectNodes("/rss/channel/item")
var iMax = itemNodes.length

sText = itemNodes.item(iNews).getElementsByTagName("title").item(0).text
myTicker.href = itemNodes.item(iNews).getElementsByTagName("link").item(0).text
ticker()
iNews+=1
if(iNews==iMax){
iNews=0
}
window.setTimeout("GetNewsSource()", (90*sText.length +4000))
}

function ticker(){
i+=1
myTicker.innerText = sText.substring(0,i) + "*"
if(i<sText.length){
window.setTimeout("ticker()",90)
}
else{
i=0
}
}
</script>
</head>
<body onLoad="GetNewsSource()">
<p><b>Yahoo! News: <a id="myTicker" href=""></a></b></p>
</body>
</html>

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.

Average rating:

Comments

why doesnt this work in ff?