A DataBound Javascript News Ticker for ASP.NET
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: ';
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.
Currently rated 4.13 by 38 people
Rate Now!
Date Posted:
25 December 2008 14:18
Last Updated:
21 January 2009 20:55
Posted by:
Mikesdotnetting
Total Views to date:
24406



Comments
06 January 2009 23:15 from 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 ?
07 January 2009 07:17 from Mikesdotnetting
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.
20 January 2009 15:09 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
20 January 2009 20:02 from Mikesdotnetting
@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.
20 March 2009 17:43 from 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
20 March 2009 19:46 from Mikesdotnetting
@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.
06 May 2009 17:44 from Khader
am getting an error Error name 'MyTicker' does not exist in the current context what am missing?
07 May 2009 20:07 from Mikesdotnetting
@Khader
Sounds like you have your literal in a ContentPanel or some such. You need to use FindControl() to reference it.
11 May 2009 11:58 from 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
11 May 2009 18:57 from 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.
11 May 2009 21:35 from Mikesdotnetting
@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.
11 May 2009 21:37 from Mikesdotnetting
@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.
11 May 2009 22:43 from 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();
}
06 June 2009 20:01 from Sayed
sorry i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me
25 June 2009 07:38 from Yasser
i get that error
Error Message: 'TickerLink' is null or not an object
can you please help me
24 July 2009 15:43 from Allan
Many thanks for posting this it, really good ticker and just what I needed.
Ta!
01 September 2009 12:13 from Naresh
This looks really great and useful.... This was the one I was searching for...
22 October 2009 06:56 from mahmoud
thank you very much
12 April 2010 16:23 from 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?
21 May 2010 00:12 from 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?
21 May 2010 05:21 from Mikesdotnetting
@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.
17 July 2010 09:04 from 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?
18 July 2010 06:39 from Mikesdotnetting
@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
08 September 2010 17:58 from luke
is there any reason why the literal is inside of javascript? As coded above i am getting a compile error because of this
11 September 2010 10:23 from Mikesdotnetting
@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.
05 April 2011 05:15 from Syamand
could you please put the complete file source code download link ...
Regards
26 June 2011 13:25 from Hosein
It's Very Good!
Thanks