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:
Last Updated:
Posted by:
Total Views to date: 44343

27 Comments

- 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 ?

- 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.

- 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

- 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.

- 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

- 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.

- Khader

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

- Mike

@Khader

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

- 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

- 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.

- 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.

- 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.

- 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();
}

- Sayed

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

- Yasser

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

- Allan

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

Ta!

- Naresh

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

- mahmoud

thank you very much

- 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?

- 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?

- 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.

- 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?

- 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

- luke

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

- 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.

- Syamand

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

Regards

- 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 I end up deleting quite a lot. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Requests to fix your code (post a question to forums.asp.net instead, please)
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam

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

faysal 3/3/2015 11:46 AM
In response to Inline Editing With The WebGrid
Nice one can you please tell us how we can do ad and delete functionality in this. for e.g if i on...

Fairoze Mohamed Musthafa 3/2/2015 8:33 AM
In response to Date formatting in VBScript
Appreciated !!!!...

mahdi 3/1/2015 10:16 AM
In response to Getting the identity of the most recently added record
Great Article....

Sohrab 2/28/2015 12:53 PM
In response to Displaying One-To-Many Relationships with Nested Repeaters
hi.this was very usefull for me.after spending 6 hours I could find best answer for my alot....

Abolfazl RoshanZamir 2/28/2015 10:36 AM
In response to Date Formatting in C#
very informative... thanks for sharing sir......

Oscar Duran 2/27/2015 2:00 PM
In response to How To Check If A Query Returns Data In ASP.NET Web Pages
Thank you very much Mike, this post has been very useful to me....

lama 2/27/2015 1:46 PM
In response to iTextSharp - Working with Fonts
thanks alot!! is it possible to add line height value to a paragraph ?...

Oded Dror 2/27/2015 5:23 AM
In response to MVC 5 with EF 6 in Visual Basic - Creating an Entity Framework Data Model
Hi there, Where I can find Contoso University Database? Thanks, Oded Dror...

hosein ey 2/25/2015 1:56 PM
In response to ASP.NET MVC 5 with EF 6 - Working With Files
tnx for this article do you think next version of entityframework support's the sql server and ?...

Saywer Ford 2/25/2015 5:15 AM
In response to Optimising ASP.NET Web Pages Sites - Bundling And Minification
Great Article. I did everything right and working fine. How about page specific js files. Lets I...