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.

 

Date Posted: Thursday, December 25, 2008 2:18 PM
Last Updated: Wednesday, January 21, 2009 8:55 PM
Posted by: Mikesdotnetting
Total Views to date: 42408

27 Comments

Tuesday, January 6, 2009 11:15 PM - Prakash

I get the error that Headlines does not exist in current context.

In the above function runTicker(), can you directly use CurrentHeadline = Headlines[StoryCounter] ???

Headlines[] is server side variable, how can it be used directly into client side java script ?

Wednesday, January 7, 2009 7:17 AM - Mike

Hi Prakash,

Headlines[] is a javascript array. You will see that it is used in the javascript <script> block. I'm not sure where you got the idea that it is a server-side variable from.

Tuesday, January 20, 2009 3:09 PM - Raju

Hello...This is really great. Is there any way to make the Headlines to scroll from bottom to top instead of from left to right...? Thanks, Raju

Tuesday, January 20, 2009 8:02 PM - Mike

@Raju

The article is about a ticker, not a scroller. You can find loads of examples of the type you are looking for by using Google to search for Javascript Scoller.

Friday, March 20, 2009 5:43 PM - Goran Hillborg

Great application!

Very useful indeed. I´m surprised there is nothing similar to find from the top .Net control vendors.

I have one small question though: Your example assumes that there are 4 records collected from the database, which also matches the ItemCount variable in the javascript. But I must set this variable to the sama as in the Sql query, or it won´t work. Do you have an easy suggestion to how I can make the number of rows/items dynamic?

Best Regards
/Goran

Friday, March 20, 2009 7:46 PM - Mike

@Goran

I would put an asp Literal control where the ItemCount is and then run a SELECT COUNT(*) on the database for the number of items that match the selection criteria. Set the value of the Literal to the result of the COUNT and away you go.

Wednesday, May 6, 2009 5:44 PM - Khader

am getting an error Error name 'MyTicker' does not exist in the current context what am missing?

Thursday, May 7, 2009 8:07 PM - Mike

@Khader

Sounds like you have your literal in a ContentPanel or some such. You need to use FindControl() to reference it.

Monday, May 11, 2009 11:58 AM - Goran Hillborg

Hi,

I haven´t checked in for a while now, thanks for your suggestion. My solution was similar to yours. The only problem is this: The ticker on my page is only used when there are any headlines to show, and if I set ItemCount to "0" IE displays the error "'CurrentHeadLine' is null or not an object". Do you have any suggestions on how I can get rid of this?

Best
/Goran

Monday, May 11, 2009 6:57 PM - Rob Strong

This so cool. I am trying to get the itemcont to be the array length (number of rows in the headlines array) but I am not having much luck. Any suggestions? I am new to Javascript.

Monday, May 11, 2009 9:35 PM - Mike

@Goran

You could make the call to startTicker() dynamic, in that once you have detected that there are headlines, you would print it to the browser - otherwise don't.

Monday, May 11, 2009 9:37 PM - Mike

@Rob

Like I suggested to Goran, you need to get the number of items from server-side code. Where I have itemCount = 4, you would put a Literal Control and set the itemCount to whatever your server-side code tells you.

Monday, May 11, 2009 10:43 PM - Goran Hillborg

Thanks Mike,

That did the trick. I have a hidden literal that holds the ItemCount number, so I just put this in the code behind:


if (ltlCount.Text != "0")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "myScript", "startTicker();", true);
MyTicker.Text = sb.ToString();
}

Saturday, June 6, 2009 8:01 PM - Sayed

sorry i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me

Thursday, June 25, 2009 7:38 AM - Yasser

i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me

Friday, July 24, 2009 3:43 PM - Allan

Many thanks for posting this it, really good ticker and just what I needed.

Ta!

Tuesday, September 1, 2009 12:13 PM - Naresh

This looks really great and useful.... This was the one I was searching for...

Thursday, October 22, 2009 6:56 AM - mahmoud

thank you very much

Monday, April 12, 2010 4:23 PM - RKD

Hello
first, thank you for the post, its usefull.
i'd like to 3 buttons next to the ticker (pause, play), next and previous. any idea?

Friday, May 21, 2010 12:12 AM - Craig

This is great, any idea how I could use two of these on a single page? I need to query two separate databases and display two tickers. I've tried using two separate web controls with all variables renamed, and two separate literal controls, but can't get them both to work at once. Any pointers?

Friday, May 21, 2010 5:21 AM - Mike

@Craig

I'm working on a jQuery version of this article which will be ready in the next day using this: http://www.makemineatriple.com/jquery/ and a couple of other tickers/scrollers. Check back soon.

Saturday, July 17, 2010 9:04 AM - Rachid

great article!! I use 2 pics to move the ticker from left to right. how can I change the code so that it moves from right to left?

Sunday, July 18, 2010 6:39 AM - Mike

@Rachid,

You will find that a lot easier to accomplish if you read my jQuery version of this article: http://www.mikesdotnetting.com/Article/138/jQuery-News-Scrollers-and-Tickers-with-a-ListView

Wednesday, September 8, 2010 5:58 PM - luke

is there any reason why the literal is inside of javascript? As coded above i am getting a compile error because of this

Saturday, September 11, 2010 10:23 AM - Mike

@luke

The lietral is inside the javascript so that the content can be changed dynamically. As far as your error is concerned, having a Literal there shouldn't give you one. Your issue is probably unrelated. The code as-is worked fine when I wrote the article.

Tuesday, April 5, 2011 5:15 AM - Syamand

could you please put the complete file source code download link ...

Regards

Sunday, June 26, 2011 1:25 PM - Hosein

It's Very Good!
Thanks
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...