Use jQuery and ASP.NET to Build a News Ticker
By Scott Mitchell
Introduction
Many websites display a news ticker of one sort or another. A news ticker is a user interface element that displays a subset of a list of items, cycling through them one at a time after a set interval. For example, on Cisco's website there is a news ticker that shows the company's latest news items. Each news item is a one sentence link, such as "Desktop Virtualization Gathers Steam," or "Cisco Reports First Quarter Earnings." Clicking a headline whisks you to a page that shows the full story. Cisco's news ticker shows one headline at a time; every few seconds the currently displayed headline fades out and the next one appears. In total, Cisco has five different headlines - the ticker displays each of the five and then starts back from the beginning.
This article is the first in a series that explores how to create your own news ticker widget using jQuery and ASP.NET. jQuery is a free, popular, open-source JavaScript library that simplifies many common client-side tasks, like event handling, DOM manipulation, and Ajax. This article kicks off the series and shows how to build a fairly simple news ticker whose contents can be specified statically in HTML markup or created dynamically from server-side code. Future installments will explore adding bells and whistles, such as: stopping the news ticker rotation when the mouse is hovered over it; adding controls to start, stop and pause the headlines; loading new headlines dynamically using Ajax; and packaging the JavaScript used by the ticker into a jQuery plugin.
Read on to learn more!
An Overview of the News Ticker's Functionality and Markup
The news ticker I've created is designed to rotate through a series of headlines that are defined in the markup of the page using an unordered list; each headline can contain any HTML, including text, images, and links. The following markup shows an example of the markup you would use to define the headlines. Note that the headlines appear as
<li> elements within a <ul> element and that while there are only two headlines in
the below markup, you could add as many as you want by adding additional <li> elements. (The <div> element that encases the
<ul> is there for styling purposes - as we'll discuss later, it specifies a width, height, and border for the list items, among other things.)
<div class="ticker threeRows medium">
|
Each <li> element represents a headline and can have any HTML you like. In the above example I have three <div> elements in
each headline with different CSS classes - header, body, and footer - for formatting the headline's header, body, and footer text.
You could add images or replace the <div>s with just text. And while not shown in the sample above, you can certainly add hyperlinks to the
markup in the <li> elements.
A news ticker may have an arbitrary number of headlines; however, only a specified number of them are shown at any given time. Every so often, the topmost headline is faded out and the next not-shown headline is displayed. Consider a news ticker with six headlines that is configured to display three headlines at a time and to show each headline for five seconds. Such a ticker would initially show just the first three headlines, like so:
- Headline 1
- Headline 2
- Headline 3
- Headline 2
- Headline 3
- Headline 4
- Headline 4
- Headline 5
- Headline 6
- Headline 5
- Headline 6
- Headline 1
setInterval
function. When the page is loaded, all but the first N list items in the <ul> element are hidden (here, N is the number of headlines
to display, such as 3). Next, an interval is created using the setInterval function, which tells JavaScript to execute some code after a
set duration (say, after five seconds) and to continually execute that code every duration. Specifically, the code setup to execute every duration fades out the
first list item in the list, removes that list item, and then adds it back to the <ul> as the last list item. The following diagram illustrates this
workflow.
Starting the News Ticker and Specifying the Number of Items to Display and the Duration
We've already seen how to define the news ticker's headlines through markup on the page. To have only a subset of the headlines displayed and to have each headline cycled through every specified number of milliseconds we need to run a bit of JavaScript. I've packaged this JavaScript in a script file named
ticker.js,
which you'll find in the Scripts folder in the sample application available for download at the end of this article. The ticker.js file
contains two functions:
startTicker(id, numberToShow, duration)- call this function when the page loads to convert an unordered list into a news ticker.rotateTicker(id)- this function is automatically invoked every duration number of milliseconds and is responsible for fading out the first list item, removing it from the unordered list, and then adding it to the bottom of the list. You would not call this function directly.
startTicker from the $(document).ready event handler.
For the id input parameter, pass in the jQuery selector syntax for the <ul> element that contains the headlines. For example, if your
<ul> element has an id of myHeadlines you'd pass in the string "#myHeadlines". The last two input parameters -
numberToShow and duration - specify the number of headlines to show at a given time and how many milliseconds to display each headline before
cycling in the next one. The duration input parameter is expressed in the number of milliseconds, so to display each headline for five seconds you'd use a
duration value of 5000.
The demo available for download at the end of this article includes a page named SimpleTicker.aspx. There you'll find two news tickers: one that displays
a short textual headline and shows only one headline at a time, and a second one that displays a more detailed headline and shows three at a time. Let's look at each
one of these tickers.
The abbreviated markup for the headlines for the first ticker (the one that shows one headline at a time) follows:
<div class="ticker stretched">
|
For starters, note the <div> element encasing the <ul>. The <div> element is assigned two CSS classes.
These classes are defined in the NewsTicker.css file and causes the ticker to have a light gray background and to be stretched across the width of its
parent element. Each individual headline has a <div> element assigned the CSS class body, which displays the text in an 8pt font.
With this markup and nothing else, all six list items would be displayed and there would be no cycling through the items over time. To have it display just one headline
and to have a new one cycled in every five seconds, say, we need to call the startTicker function in the $(document).ready event handler:
<script type="text/javascript">
|
Note: In addition to the above JavaScript, you'll also need to reference the jQuery library and ticker.js script file for the above script to
work. In the demo application these script references are located in the master page, Site.master.
With the above markup and script in place, visiting the page displays the unordered list as a single line, showing the first list item as the headline.
After five seconds, the first headline fades out and the second one appears.
The news ticker that shows three items at a time has a similar setup as the single headline ticker. We already say its headline markup (refer back to the first
code listing in this article). For this news ticker we show more details with each item, including a header and the time it was published. Also, three headlines are shown
at a time. Because we want to show three headlines at a time (instead of one) we pass in different input parameters to the startTicker function:
<script type="text/javascript">
|
The result is a news ticker with three items displayed at once. Just like with the single item news ticker, every five seconds the top-most headline fades out and the next three are displayed.
Creating the Headlines from Server-Side Code
The
SimpleTicker.aspx demo shows how to define headlines as hard-coded, static markup in the page. Oftentimes, though, the headlines for display are
stored in a database or XML file. To show these headlines in the news ticker we need to write a bit of server-side code that gets the headlines of interest and
renders the appropriate markup.
The DynamicTicker.aspx demo displays the most recent tweets from my Twitter account (@ScottOnWriting) in the news ticker format.
Every Twitter account has an RSS feed that returns the most recent tweets for a particular user. The DynamicTicker.aspx demo retrieves this RSS feed using
the SyndicationFeed class and binds the resulting
items to a ListView, which emits the appropriate unordered list markup.
Let's start by looking at the ListView markup. The ListView contains a LayoutTemplate that creates an unordered list with an id of tweets.
The contents of the unordered list are generated by the ItemTemplate, which creates an <li> element that displays the
tweet text (Eval("Summary.Text")) and the date the tweet was made (Eval("PublishDate.DateTime")). These two inputs are passed into formatting
methods - FormatSummary and FormatPubDate - which are both defined in the code-behind class and tidy up the output for display.
<asp:ListView ID="lvTweets" runat="server">
|
In addition to the ListView markup we also need to call the JavaScript startTicker function when the document loads. Here we configure it to show two tweets
at a time for four and a half seconds.
<script type="text/javascript">
|
The page's code-behind class contains a Page_Load event handler and the two formatting methods, FormatSummary and FormatPubDate. The
Page_Load event handler starts by getting my recent tweets, which are accessible as an RSS feed at the URL
http://twitter.com/statuses/user_timeline/174828949.rss. As discussed in
How to create a syndication feed for your website,
the .NET Framework's SyndicationFeed class makes it a cinch to work with RSS feeds. As the code shows below, you can read an entire RSS feed from an
external URL in one line of code. Once this RSS feed has been read, its items are bound to the ListView.
Each tweet returned by the RSS feed starts with my Twitter user name, ScottOnWriting. For example, if I tweet, "ASP.NET is fun," the RSS feed will report the tweet
as "ScottOnWriting: ASP.NET is fun." The FormatSummary formatting method strips out this header text and returns just what follows it. The
FormatPubDate method takes the date and time the tweet was made and formats it to show the hour, minute, abbreviated month name, and day of month.
(See Formatting Dates, Times and Numbers in ASP.NET for more information on how to format dates.)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
|
That's all there is to it! With just a few lines of server-side code and with just a touch of markup in the ListView's templates, we have a news ticker that shows my latest tweets. Of course, you are not limited to just displaying tweets as the headlines in your news ticker. Rather, you can show any content that you can pull from any source, be it from a database, RSS feed, XML file, or any other store.
Conclusion and Looking Forward...
At this point we have a simple, functional news ticker. There are some usability features that would be nice to add, such as having the cycling pause when hovering over the news ticker with your mouse and offering users the ability to move between headlines or to stop, start, and pause the ticker. Also, it would be nice to be able to customize the configuration further, such as replacing the existing fade out effect with an alternate one. Finally, it would be nice to be able to programmatically start, stop, and pause the ticker, as well as to move to a particular headline. These features, among others, will be explored in future articles in this series.
Until then... Happy Programming!
Attachments:
Further Reading