A DataBound Javascript News Ticker for ASP.NET

It's funny how requirements come along like buses in the ASP.NET forums - you suddenly get the same thing asked for by two or more people in quick succession. Recently, a couple of people asked for help creating a Javascript ticker, like the one at the top of the BBC News site, which displays a selected number of headlines drawn from a database. I had adapted the code from the BBC site to create a similar widget that displayed the most recent threads in a message board on an old Classic ASP site some time ago. It's about time I dusted it off and updated it for use in an ASP.NET application.

To keep things relatively simple, I've created the ticker as a User Control, which is the ASP.NET successor to my original Server-Side Include file. The ascx file will hold the Javascript and the ascx.cs file will contain the data access code. First the Javascript:

 

<script language="JavaScript" type="text/javascript">

 

var CharacterTimeout = 50;

var StoryTimeout = 3000;

var SymbolOne = '_';

var SymbolTwo = '-';

var SymbolNone = '';

var LeadString = 'LATEST:&nbsp;&nbsp;&nbsp;';

var Headlines = new Array();

var Links = new Array();

var ItemCount = 4;

 

<asp:Literal ID="MyTicker" runat="server" />

 

function startTicker() {

 StoryCounter = -1;

 LengthCounter = 0;

 TickerLink = document.getElementById("tickerlink");

 runTicker();

}

 

function runTicker() {

 var Timeout;

 if (LengthCounter == 0) {

  StoryCounter++;

  StoryCounter = StoryCounter % ItemCount;

  CurrentHeadline = Headlines[StoryCounter];

  TargetLink = Links[StoryCounter];

  TickerLink.href = TargetLink;

  Prefix = "<span class=\"ticker\">" + LeadString + "</span>";

 }

 

 TickerLink.innerHTML = Prefix + CurrentHeadline.substring(0, LengthCounter) + getSymbol();

 

 if (LengthCounter != CurrentHeadline.length) {

  LengthCounter++;

  Timeout = CharacterTimeout;

 }

 else {

  LengthCounter = 0;

  Timeout = StoryTimeout;

 }

 setTimeout("runTicker()", Timeout);

}

 

function getSymbol() {

 if (LengthCounter == CurrentHeadline.length) {

  return SymbolNone;

 }

 if ((LengthCounter % 2) == 1) {

  return SymbolOne;

 }

 else {

  return SymbolTwo;

 }

}

 

startTicker();

</script>

 

The Javascript starts with a set of variables being defined. CharacterTimeout and StoryTimeout respectively set the delay between the addition of characters to the headline, and the next story appearing. Three symbols are created, which give the appearance of a typewriter or old-fashioned teletype running as characters are appended to the headline. Finally, and array is set for the headlines, and one for the links, followed by the total number of headlines that will be managed by the ticker.

Next, an asp:Literal control is added. This will serve as a placeholder for the array of headlines and links that will be retrieved from the database. This is followed by the three functions that do the brunt of the work:

startTicker()
startTicker() intialises the ticker by setting some counters to their starting values, and then it locates the <a> tag that will display the links. The <a> tag has not been added yet, but should appear at the top of the ascx file:

 

<div>

  <a id="tickerlink" href="#" style="text-decoration: none;"></a>

</div>

 

Finally, it calls the next function:

runTicker()
LengthCounter holds the current position within the current headline. If the headline has finished, or not been started at all, the counter is set to 0. The StoryCounter, which was initialised at -1 is set to 0, or the next headline in the array. The link that matches the headline is also referenced. Then the initial text in the ticker is picked up and set inside a <span> that holds a CSS class attribute so that it can be styled. Then the <a> link text is set to hold the current headline together with its link and a symbol retrieved using the getSymbol() function. Some checks are made to calculate whether the current headline has been written, or is in the process of being written, then the runTicker() function is called with the value of TimeOut having been ascertained.

getSymbol()
This function is pretty simple. All it does is to alternate between symbols - either a hyphen or an underline - depending on whether the position reached within the string containing the headline is odd or even. If the end of the string hass been reached, the symbol is an empty string.

Last of all, the first function, startTicker() is called.

Now to the code-behind file for the user control:

 

StringBuilder sb = new StringBuilder();

string connect = ConfigurationManager.ConnectionStrings["myConnString"].ConnectionString;

using (SqlConnection conn = new SqlConnection(connect))

{

  string query = "SELECT TOP 4 ArticleID, Headline FROM Articles ORDER BY ArticleID DESC";

  SqlCommand cmd = new SqlCommand(query, conn);

  conn.Open();

  using (SqlDataReader rdr = cmd.ExecuteReader())

  {

    int i = 0;

    while (rdr.Read())

    {

      sb.Append("Headlines[" + i.ToString() + "] = '" + rdr[1].ToString() + "';");

      sb.Append("Links[" + i.ToString() + "] = '/Article.aspx?ArticleID=" + rdr[0].ToString() + "';");

      i++;

    }

  }

}

MyTicker.Text = sb.ToString();

 

This is very straightforward too. Remembering to reference System.Data.SqlClient, System.Text and System.Configuration, the code simply connects to a database and gets the most recent 4 headlines in the database together with their ID so that links can be written. While looping through a DataReader, a StringBuilder object is built up containing the text for the headlines and the links. This is set to generate an array for the headlines and one for the links to populate the ones that were instantiated in the Javascript earlier. Finally, the contents of the StringBuilder are passed to the Literal control in the ascx file. And that is it.

The Javascript above looks quite complex at first glance, but hopefully, you can now see that it actually very straightforward.