For our first rotator
example, we'll take a news feed and scroll the headlines, along with an
excerpt of the article, into view one at a time. The stories will flow
into view, pause to be read, and then slide up and off the page as if
there were an infinite ribbon of information rolling over the page.
Setting up the page
At its most basic level, this
feature is not very difficult to implement. But as we will soon see,
making it production-ready requires a bit of finesse.
We begin, as usual, with a chunk of HTML. We'll place the news feed in the sidebar of the page:
<a href="news/index.html">News Releases</a>
So far, the content area of our news feed contains only a single link to the main news page.
The CSS for this<div>
is important as it will determine not only how much of each news item
will be shown at a time, but also where on the page the news items will
appear. Together with the style rule for the individual news items, the
CSS looks like this:
headline rotatorpage, setting upposition: relative;
Notice here that the height of both the individual news items (represented by the headline class) and their container is 200px. Also, since headline elements are absolutely positioned relative to #news-feed, we're able to line up the top of the news items with the bottom edge of their container. That way, when we set the property of #news-feed to hidden, the headlines are not displayed initially. overflow
Setting the position of the headlines to absolute is necessary for another reason as well: for any element to have its location animated on the page, it must have either or relative positioning, rather than the default static positioning. absolute
Now that we have the HTML and CSS in place, we can inject the news items from an RSS feed. To start, we'll wrap the code in a .each() method, which will act as an if statement of sorts and contain the code inside a private namespace:
var $container = $(this);
Normally when we use the .each() method, we are iterating over a possibly large set of elements. Here, though, our selector #news-feed
is looking for an ID, so there are only two potential outcomes. The
factory function could make a jQuery object matching one unique element
with the news-feed ID, or it could find no elements on the page with that ID and produce an empty jQuery object. The .each() call takes care of executing the contained code if, and only if, the jQuery object is non-empty.
At the beginning of our .each() loop, the news feed container is emptied to make it ready for its new content.