• Feed RSS

jQuery Tutorial: Building a jQuery Scroller

"

Building a jQuery News Scroller

If you’re working on a site where a number of important stories or features need to be showcased within a small area, a news scroller is a great option. Without taking up much page real estate, you can highlight several stories along with descriptions and links to view the details. The scrolling effect helps attract and hold user interest. In this tutorial, I’ll guide you through the easy process of creating this type of news scroller with jQuery. We’ll start with an HTML list of stories that’s styled using CSS, then use jQuery to make it automatically scroll. When the user hovers over the jQuery Scroller, it will pause so they can read the abstract and click the link if they’re interested.
Before getting started, be sure to view the demo to see how the scroller works. Here’s what the finished project will look like:
finished

jQuery Scroller Tutorial Details

  • Technologies: HTML, CSS, JavaScript, jQuery
  • Difficulty: Intermediate
  • Estimated Completion Time: 20-30 minutes

Intro: Preparations

You should create an empty HTML file and save it somewhere convenient now; we’ll be working with it throughout this tutorial. Because we’ll be working exclusively with client-side code, there’s no need for a server – you can preview directly on your computer. In the demo files we’ll use inline CSS and JavaScript, but you can externalize these if desired.
Tip: For this type of tutorial, it can be helpful to use jsBin or jsFiddle to follow along. These free online tools let you experiment with HTML, JavaScript and CSS without having to create any files on your computer. Best of all, you can save, version and share your experiments. It’s a great way to perfect a technique without cluttering up your computer with tons of files.
If you’re creating your own HTML file, here’s the code you should have to start:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

 <title>jQuery News Scroller</title>
 <style type="text/css">
 /* CSS will go here */

 </style>
</head>

<body>

 <!-- Markup will go here -->

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
 <script type="text/javascript">
 // JavaScript will go here

 </script>
</body>
</html>
Note the designated places for markup, CSS and JavaScript. Additionally, note that we have included jQuery 1.6.1 from Google’s CDN.

Step 1: The HTML Markup

We’ll use a dedicated <div> to hold the scroller. In keeping with best practices, all of the content will be placed in an unordered list (<ul>), with a list item (<li>) for each separate story. By using an HTML list to define the links, we ensure that the ticker will gracefully degrade for users with JavaScript disabled, and that search engines will still be able to see and follow all of the links. Add the following HTML markup to your page:
<div class="newsScroller" id="newsScroll">
   <ul>
       <li>
           <a class="title" href="#">My Story 1</a>
           <span class="desc">
               Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
           </span>
           <a class="link" href="#">More...</a>
       </li>
       <li>
           <a class="title" href="#">My Story 2</a>
           <span class="desc">
               Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
           </span>
           <a class="link" href="#">More...</a>
       </li>
       <li>
           <a class="title" href="#">My Story 3</a>
           <span class="desc">
               Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
           </span>
           <a class="link" href="#">More...</a>
       </li>
       <li>
           <a class="title" href="#">My Company's News Ticker</a>
           <span class="desc">
               &copy; 2011 My Company
           </span>
       </li>
   </ul>
</div>
We have four items: three stories, then a quick ‘about’ item with a copyright. For each of the real items, there’s a title link to the story, a description, and another “more” link to the story at the bottom. If desired, you can customize this structure once you’ve completed the project. The nice thing about the way we’re going to build this is that you can place anything within the <li> items – including images or any other markup.
Update the list now to contain an <li> for each of the features you want in the scroller.

Step 2: Styling

If you preview now, you’ll see a simple HTML list of stories complete with links. Now it’s time to make the jQuery Scrollerlook nice and take the first step towards interaction.
We’re going to explicitly specify width and height dimensions for the wrapper <div>, then use the overflow property to make the user be able to scroll through the list of links (since there’s more content than fits within the specified size). In a minute we’ll override part of this CSS with JavaScript so that the scrolling happens automatically and no scrollbar shows, but we want the CSS default to allow for user control. This way, the scroller will still be usable even if the user has disabled JavaScript.
In the <style> tag in the <head>, add the following CSS:
.newsScroller {
   height: 120px;
   width: 260px;
   overflow-x: hidden;
   overflow-y: scroll;
   font: 10px/15px Verdana,Arial,sans-serif;
   color: #333;
   border: 1px solid #999;
}
.newsScroller ul {
   margin: 0;
   padding: 4px;
}
.newsScroller li {
   list-style-type: none;
   margin: 0 0 16px 0;
   padding: 0;
}
.newsScroller a.title {
   display: block;
   font-weight: bold;
   text-transform:uppercase;
   text-decoration: none;
}
.newsScroller a.title, .newsScroller a.title:visited, .newsScroller a.title:hover {
   color: #F90;
}
.newsScroller a.title:hover
{
   text-decoration: underline;
}
First, we add the dimensions and scrollbar to the jQuery Scroller, along with some basic font styling and a border. Next, we reset the margins and padding for the HTML list and its items, also disabling the default list bullets. We end up with a block of items that have some spacing around all of them and between each of them. Finally, we add some basic styling to each of the links. You can customize this styling as desired.
If you preview now, you’ll see something remarkably similar to the finished product:
no_js_preview
This is what anyone with JavaScript disabled will see. Even though it’s not optimal, it’s still fully functional – which is what we were aiming for. This approach represents the best practice of progressive enhancement; the content is always usable, but the more advanced a user’s browsing environment is, the more functionality they’ll receive.

Step 3: Making It Work

Now we’re ready to add the jQuery-enhanced JavaScript to make the jQuery Scroller work automatically. I’ll show you the overall chunk first, then break down what each portion is doing.
Add the following chunk of JavaScript to the <script> tag at the bottom of the page:
$(function()
{
   $('#newsScroll').each(function()
   {
       var scroller = $(this);
       var list = scroller.children('ul');

       var listH = list.height();
       var scrollerH = scroller.height();
       list.css({
           marginTop: scrollerH,
           marginBottom: scrollerH
       });
       scroller.css({
           overflow: 'hidden'
       });

       var isOver = false;
       scroller.bind('mouseenter mouseleave', function(e) {
           isOver = (e.type == 'mouseenter');
       });

       var scroll = 0;
       setInterval(function()
       {
           if (isOver) return;
           scroll++;
           var newTop = scroll % (listH + scrollerH);
           scroller.scrollTop(newTop);
       }, 30);

   });
});
If you preview now, you should see the working jQuery Scrollerthat scrolls through all of your feature items. If you hover over the scroller, it will pause; if you move your mouse away again, it will continue. Now, let’s break down what all of that code is doing.
Breaking Down the JavaScript – Overview
In plain English, here’s what the JavaScript is doing:
  • Everything is wrapped in a document-ready trigger, so it will be called once the document is ready for manipulation
  • We locate the news jQuery Scroller and its content
  • We measure the wrapper and the contents so we know how far to scroll
  • We override the default CSS with the appropriate styles to make auto-scrolling work properly
  • We create a listener for mouse interaction with the jQuery Scroller
  • We start the auto-scroller timer
Breaking Down the JavaScript – Details
Now, lets take an in-depth look at what each of these pieces of code is doing.
Note that we use the #newsScroll selector to locate the scroller. If you had multiple scrollers in your page, you could change this to div.newsScroller instead, since we applied a class of newsScroller to our jQuery Scroller.
Chunk 1 – Finding the content
var scroller = $(this);
var list = this.children('ul');
In this first chunk, we create a jQuery reference to the current scroller. Then, we locate the actual list (the content that will be scrolled).
Chunk 2 – Making measurements, Updating CSS styles
var listH = list.height();
var scrollerH = scroller.height();
list.css({
   marginTop: scrollerH,
   marginBottom: scrollerH
});
scroller.css({
   overflow: 'hidden'
});
In this next major chunk, we first measure the list’s height and the scroller’s height. These measurements are needed so that we can then apply extra space to each end (via margin-top and margin-bottom), and later know how much scrolling is needed. Without adding the extra space, the scrolling would have a disturbing “jump” when first starting and then when looping. Here’s a diagram explaining what we want:
scrolling_diagram
We start at the Initial State. The content chunk scrolls vertically for [content height] + [visible box height] pixels, until we reach the End State, then immediately resets to the Initial State again. The end result is that there’s a short empty space on each loop, letting the user know that the scroller is looping.
Finally in the chunk, we remove the default scrollbars by overriding the overflow property that was set earlier via a CSS rule.
Chunk 3 – Detecting user interaction
var isOver = false;
scroller.bind('mouseenter mouseleave', function(e) {
   isOver = (e.type == 'mouseenter');
});
Because we want the jQuery Scroller to pause when the user hovers over it, we need to add a mouseenter listener. Correspondingly, we also need to add a mouseleave listener for un-pausing it. In this chunk, we create a variable to track whether the user is over the scroller, then add a compound listener that updates that variable whenever there’s interaction. By using a single listener for both events and looking at the event.type property, we create code that’s more compact, efficient and readable. The isOver flag will be used in the next chunk to control pausing.
Chunk 4 – Starting the auto-scrolling
var scroll = 0;
setInterval(function()
{
   if (isOver) return;
   scroll++;
   var newTop = scroll % (listH + scrollerH);
   scroller.scrollTop(newTop);
}, 30);
First, we create a tracker for the scrolling position. Then, we start an interval that calls a scroll function every 30 milliseconds. To reduce the speed of the jQuery Scroller, this value should be increased; to speed it up, this value should be decreased. In the scroll function, we immediately exit if the user is currently hovering over the scroller. This makes the scroller pause when hovered-over. Otherwise, we first increment the scroll position tracker. Then, we use the modulus operator (%) to calculate the new appropriate scroll position. Finally, we apply that new scroll position. In calculating the scroll position, note that we loop after reaching [height of list] + [height of content], as described earlier and shown in the diagram.

Summary

You’ve now created a simple news jQuery Scroller to display featured story snippets on your site. The scroller features cross-browser compatibility, progressive enhancement, and automatically pauses and resumes based on user interaction. To enhance the scroller, you could start adding images and other content to the snippets, or use a server-side script (like PHP) to dynamically output the snippets and links. There are numerous possibilities! Moreover, you’ve learned about how jQuery’s document querying and manipulation methods can be leveraged to quickly and easily create nifty, useful widgets for your page. Have fun with your new knowledge!

Author : Nathan Rohler

Nathan Rohler, who works as the lead developer for DWUser.com, is passionate about creating beautiful and moving web experiences. DWUser.com offers software tools for developers and designers, including an easy and free jQuery slider builder, EasyRotator.
"