A Javascript News Ticker

News tickers are common in news websites. A news ticker is usually used to draw user’s attention to the site’s latest news headlines. It can also provide a direct link to the displayed news item so that readers can immediately access the full content from anywhere within the site. One such ticker can be seen at the Philippines Today website. This post describes how to create a simple news ticker you can use on your own website using javascript.

To start with, we define two arrays. One contains the titles of the news items to be displayed and the other the links to access these items. Here, we will explicitly specify the titles and the links within the code for simplicity. Other methods, such as via RSS, can be used to implement automatic retrieval of titles and links that will be displayed in the ticker. But this will not be covered here. Our first javascript code will be like this:

var items = new Array();
var links = new Array();

items[0] = "This is the first headline.";
links[0] = "item1.htm";
items[1] = "This is the second headline.";
links[1] = "item2.htm";
items[2] = "This is the third headline.";
links[2] = "item3.htm";

Replace the sample titles and links in the above code with your own. Next, we need a function to display the news items one at a time. Call this function newsticker(). For this, we need to define a counter variable, say ctr, that will keep tab of which item in the items array is currently displayed. This counter variable will be incremented everytime the newsticker function is called. This means that to loop over the different news items, newsticker needs to be called repeatedly. To do this, we will employ javascript’s window.setTimeout function. This function can be used to call another function after a predefined time interval expressed in milliseconds. We now define newsticker as follows:

var ctr = 0;   // index pointer of current item
var curr = ""; // current text in ticker

function newsticker() {
    curr = items[ctr];
    myTicker.innerHTML = "<a href='"+links[ctr]+"'>"+curr+"</a>";
    if (ctr < items.length-1) {
        ctr++;
    } else {
        ctr = 0;
    }
    setTimeout('newsticker()',5000);
}

The first two lines will initialize the variables ctr and curr. curr is used to hold the current title to be displayed in the ticker. Inside the newsticker function, curr is assigned to the item pointed to by ctr. The innerHTML value of "myTicker" is then assigned to a linked title of the current news item. The ctr variable is checked then if it is already pointing to the last item. If it is not, its value is incremented to point to the next item in the array. Otherwise, its value is reset to zero to point again to the first item.

This basically completes the javascript part of the ticker. But we still need to place the ticker somewhere in the webpage. To do this, just put an HTML element with a "myTicker" id within the page’s body. For instance, you can put the ticker within a <div> element. As an example, here is an HTML code for a page containing only the ticker:

<body onLoad="newsticker()">
    <div id="myTicker"></div>
</body>

Be sure to assign newsticker to the onLoad function of the <body> tag. This will ensure that when the page is loaded, the newsticker function is called triggering the display of the news items.

For completeness, here’s the full source.

<html>
<head>
<title>News Ticker</title>
<script language="JavaScript" type="text/JavaScript">

var ctr = 0;  // index pointer of current item
var curr = "" // current text in ticker 

var items = new Array();
var links = new Array(); 

items[0] = "This is the first headline.";
links[0] = "item1.htm";
items[1] = "This is the second headline.";
links[1] = "item2.htm";
items[2] = "This is the third headline.";
links[2] = "item3.htm";

function newsticker() {
    curr = items[ctr];
    myTicker.innerHTML = "<a href='"+links[ctr]+"'>"+curr+"</a>";
    if (ctr < items.length-1) {
        ctr++;
    } else {
        ctr = 0; 
    }
    setTimeout('newsticker()',5000);
}
</script> 
</head>

<body onLoad="newsticker()">
    <div id="myTicker">Ticker disabled.</div>
</body>
</html>

The above describes a very simple yet working news ticker javascript. Several improvements can still be incorporated. For instance, if you don’t like your headlines to have underlines when displayed, you can revise the part where myTicker.innerHTML is defined. Add a CSS style in the link and set text-decoration to none. The revised version will be like this:

myTicker.innerHTML 
    = "<a href='"+links[cnt]+"' style='text-decoration:none;'>"+curr+"</a>"

It is also possible to revise the newsticker function to have some animation in displaying the title. For instance, instead of displaying the title at once, we can put one character at a time, imitating a "typing" effect. The revised newsticker function to implement this is as follows:

var i = 0; // title character counter

function newsticker() {

    // next character of current item
    if (i < items[ctr].length) {
        i++;
        curr = items[ctr].substring(0,i) + '_';
        myTicker.innerHTML 
            = "<a href='"+links[ctr]+"' style='text-decoration:none;'>"+curr+"</a>";
        setTimeout('newsticker()',100);
        return;
    }
    // new item
    i = 0;
    if (ctr < items.length-1) {
        ctr++;
    } else {
        ctr=0;
    }
    setTimeout('newsticker()',5000);
}

The main difference between the current version and the first one is the conditional statement at the beginning of the function. This condition checks whether the entire title is already displayed. If not, a new character is added to curr by incrementing the pointer i. The function is scheduled to be called again after 100 ms by calling the setTimeout function. This process is repeated until all the characters in the title are displayed. When this happens, i is reset to zero and ctr is incremented to point to the next title in the same way as we did in the first version.

And there you go, your own news ticker on your own website.

You may also like...

1 Response

  1. March 14, 2008

    […] this post, we will combine the two scripts described in the last two entries, namely, A Javascript News Ticker and Extending phpWebSite for mobile access, into a single script that will display in a news ticker […]

Leave a Reply