Creating Fading Headlines with jQuery in 5 minutes

We see fading headlines on the Apple site as well as lots of news and media websites.  Rather than listing all of headlines in a “stack”, they use much less real estate by having all headlines displayed in a smaller space, with headlines fading in and out over each other.  Whether you like this or not is not the point.  Showing how you can build this quickly, is.

Since I’m a big fan of the jQuery library I decided to see what it would take to build this with the help of this popular JavaScript library.  As expected, it proved to be very simple and I’m posting it here in case someone finds it handy.  It might also serve as a good interview question for candidates who claim to be proficient with JavaScript and jQuery.

The simplest way to represent a headline list is to use an unordered list:

<ul id="headlines">
<li>First News Item</li>
<li>Second News Item</li>
<li>Third News Item</li>
</ul>

This means that whether your headlines are managed by a Content Management System (CMS) or by hand, the JavaScript for the animated (fading) presentation is completely separated (unobtrusive).  This also means that all headlines are in the XHTML source and visible to search engines.

We’ll add a CSS style to remove bullets since we don’t want them:

<style type="text/css">
ul {list-style:none; margin:0; padding:0;}
</style>

Here’s the logic for making making this work (drop this in the HEAD tag or an external file).  Click here to see it in action.

[code='js']
// assumes jQuery is available

// when DOM is ready...
$(document).ready(function(){
	$("#headlines li").hide();

	var headlineFadeSpeed = 5000;
	function showNextItem(){
		var index      = arguments[0] || 1;
		var $curLi     = $("#headlines li:nth-child("+index+")");
		var totalItems = $("#headlines li").length;

		$curLi.fadeIn("fast", function(){
			setTimeout(function(){
				$curLi.fadeOut("slow", function(){
					index = (index < totalItems) ? index+1 : 1;
					showNextItem(index);
				});
			}, headlineFadeSpeed);
		});
	}

	showNextItem();
});
[/code]

And that's it.