DWUser.com

Empowering Web Creativity

Back to Education Center Home:  Go Back        Font size:  Smaller  Larger         Font weight:  Lighter  Heavier 

Tutorial: Creating a jQuery Image Scroller

by Nathan Rohler

We've received several requests for a tutorial showing how to create an image scroller or carousel – something that's not quite covered by either EasyRotator or the XML Flash Slideshow Creator v4. In this tutorial, I'll walk you through the simple steps. Here's what we're going to create:

For this demo, I haven't added any links, but they are easy to add. Note that hovering over the scroller makes it pause, and that the photos loop infinitely if you allow them to continue scrolling.

Prerequisites

We're going to be using basic HTML, CSS and JavaScript (plus jQuery) to create this scroller. If JavaScript and jQuery are new animals to you, I recommend you review Eloquent JavaScript and jQuery Fundamentals, two excellent and free eBooks linked in this article.

Writing the HTML

To get started, create a new HTML 5 document:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>Image Scroller</title>
</head>
<body>

</body>
</html>

Now, add the following markup inside the <body>:

<div id="scroller" style="width: 550px; height: 400px; margin: 0 auto;">
    <div class="innerScrollArea">
        <ul>
            <!-- Define photos here -->
            <li><img src="images/image1.jpg" width="600" height="400" /></li>
            <li><img src="images/image2.jpg" width="267" height="400" /></li>
            <li><img src="images/image3.jpg" width="600" height="400" /></li>
            <li><img src="images/image4.jpg" width="535" height="400" /></li>
            <li><img src="images/image5.jpg" width="267" height="400" /></li>
            <li><img src="images/image6.jpg" width="267" height="400" /></li>
        </ul>
    </div>
</div>

Update the <img> elements to point to your actual photos and include their real dimensions. Our demo has six photos, but you can add or remove lines depending on how many photos you would like to use. Note that all photos have the same height (400); this is important when creating this type of scroller.

Here's an example of a line with a link applied to the photo:

<li><a href="somewhere.html"><img src="images/image1.jpg" width="600" height="400" /></a></li>

If you preview your page, you'll see something like this – just a jumble of photos:

Step 1 demo

So, what exactly do we have here? First, we have a <div> that will be our scroller, identified by id="scroller". We have set the dimensions and applied a margin to center the div:

<div id="scroller" style="width: 550px; height: 400px; margin: 0 auto;">

You can set the width and height values to whatever you want the final scroller size to be, but the height should match the height of the photos.

Inside the main holder div, we have a second holder div (<div class="innerScrollArea">) that will be the part that actually scrolls. Finally, inside the inner holder div, we have the unordered list that holds all of our photos.

Adding Some CSS

Now, let's make this look a bit more like a scroller. Add the following chunk of CSS to the <head> of your page:

<style type="text/css">
    #scroller {
        position: relative;
    }
    #scroller .innerScrollArea {
        overflow: hidden;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
    #scroller ul {
        padding: 0;
        margin: 0;
        position: relative;
    }
    #scroller li {
        padding: 0;
        margin: 0;
        list-style-type: none;
        position: absolute;
    }
</style>

If you preview again, your scroller is now just a stack of photos! Believe it or not, though, we're getting closer. Let's walk through what the CSS that we just added actually does:

<style type="text/css">
    On the main scroller, use relative positioning. This allows the option of adding things such as edge overlays later if desired.
    #scroller {
        position: relative;
    }
    For the inner holder, we clip anything that runs over, via "overflow: hidden".  We position the holder to fully fill its parent, the #scroller div.
    #scroller .innerScrollArea {
        overflow: hidden;
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
    }
    On the unordered list that holds our photos, we remove the default margin and padding.  We also use "position: relative" so the list items can be laid out in a horizontal row.
    #scroller ul {
        padding: 0;
        margin: 0;
        position: relative;
    }
    On the individual list items, we remove the default padding, margin and list bullets.  The position is set to absolute; we'll use JavaScript to set the precise left positioning value.
    #scroller li {
        padding: 0;
        margin: 0;
        list-style-type: none;
        position: absolute;
    }
</style>

Adding the JavaScript

Let's get to the meat of things: the JavaScript that makes our scroller actually become a scroller. There are two parts to the code we'll be adding. The first lays out the photos horizontally and clones them so they can appear to scroll infinitely. The second part makes them scroll automatically.

To understand what we are going to do to make the slides scroll infinitely, consider the following simplified animation:

1

The red box represents the only part we actually see in the finished scroller. The first five photos, numbered 1 through 5, are the originals; but the next five photos (again numbered 1 to 5) are clones of the originals. We scroll until we can reset to the beginning, at which point the animation begins again. If you focus on the red "viewport" box, it looks like the photos go on forever.

To get started, add the following code to your page just before the closing </body> tag:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        scrollerContent.children().clone().appendTo(scrollerContent);
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        var fullW = curX / 2;
        var viewportW = scroller.width();

        scroller.css('overflow-x', 'auto');
    });
</script>

If you preview now, the scroller finally looks like a manual scroller. The photos have been cloned and can be navigated by manually scrolling.

The code I just gave you is actually incomplete. I'll give you the complete code momentarily, but I wanted you to see this intermediate step since it shows what's happening "under the hood." Let's walk through the intermediate code:

First, we include jQuery in our page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
    All of our code is wrapped in a jQuery.ready handler that executes as soon as the document is ready for manipulation.
    $(function(){
        We first get references to the scroller and its content.
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        Next, we clone the list items and add them to the list.
        scrollerContent.children().clone().appendTo(scrollerContent);
        Now, it's time to lay out the slides into a horizontal row.  We create an incremental counter, curX, and then loop through all of the slides, setting the 'left' CSS position.
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        We need to calculate the overall width of the original (non-cloned) slides and the viewport width.  These will be used to determine the scrolling behavior, which we'll add in a second.
        var fullW = curX / 2;
        var viewportW = scroller.width();
        
        This is a temporary line that we'll remove in the completed code; it just enables manual scrolling so we can see how the slides look in the demo.
        scroller.css('overflow-x', 'auto');
    });
</script>

The Real JavaScript

Of course, we don't want the scroller to be navigated manually – we want it to scroll automatically and pause when hovered-over. So replace the JavaScript code you added a moment ago with this complete code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        var scroller = $('#scroller div.innerScrollArea');
        var scrollerContent = scroller.children('ul');
        scrollerContent.children().clone().appendTo(scrollerContent);
        var curX = 0;
        scrollerContent.children().each(function(){
            var $this = $(this);
            $this.css('left', curX);
            curX += $this.outerWidth(true);
        });
        var fullW = curX / 2;
        var viewportW = scroller.width();

        // Scrolling speed management
        var controller = {curSpeed:0, fullSpeed:2};
        var $controller = $(controller);
        var tweenToNewSpeed = function(newSpeed, duration)
        {
            if (duration === undefined)
                duration = 600;
            $controller.stop(true).animate({curSpeed:newSpeed}, duration);
        };

        // Pause on hover
        scroller.hover(function(){
            tweenToNewSpeed(0);
        }, function(){
            tweenToNewSpeed(controller.fullSpeed);
        });

        // Scrolling management; start the automatical scrolling
        var doScroll = function()
        {
            var curX = scroller.scrollLeft();
            var newX = curX + controller.curSpeed;
            if (newX > fullW*2 - viewportW)
                newX -= fullW;
            scroller.scrollLeft(newX);
        };
        setInterval(doScroll, 20);
        tweenToNewSpeed(controller.fullSpeed);
    });
</script>

If you preview now, you'll see your fully-functional, completed scroller:

Completed scroller

As with the demo at the top of this page, you can hover over the scroller to pause it. (If your page doesn't work as expected, view the source code of the completed demo and compare your page to check for errors.)

Let's analyze the new chunk from the code above:

        ...

        First, we have a slightly non-traditional use of the jQuery .animate() method.  We use it to tween (animate) speed changes in our scroller, avoiding jerky stops and starts.
        // Scrolling speed management
        var controller = {curSpeed:0, fullSpeed:2}; The fullSpeed:2 value can be changed to adjust the scrolling speed.
        var $controller = $(controller);
        var tweenToNewSpeed = function(newSpeed, duration)
        {
            if (duration === undefined)
                duration = 600; This value can be changed to make the rotator stop and start more quickly or slowly.
            $controller.stop(true).animate({curSpeed:newSpeed}, duration);
        };

        We use the .hover() method to listen for mouse interaction, pausing and resuming the scroller on hover and hover-out respectively.
        // Pause on hover
        scroller.hover(function(){
            tweenToNewSpeed(0);
        }, function(){
            tweenToNewSpeed(controller.fullSpeed);
        });

        Here, we define the scrolling method that will be called ever 1/50th of a second.  It scrolls the content, looping back as needed - just as in the animation above.
        // Scrolling management; start the automatical scrolling
        var doScroll = function()
        {
            var curX = scroller.scrollLeft();
            var newX = curX + controller.curSpeed;
            if (newX > fullW*2 - viewportW)  Whenever we reach the end, we jump back.
                newX -= fullW;
            scroller.scrollLeft(newX);  We use the jQuery .scrollLeft() method to get and apply the scroll position.
        };
        Finally, we use setInterval to call the scrolling method every 20 milliseconds.  We also set the scrolling speed to "full steam ahead."
        setInterval(doScroll, 20);
        tweenToNewSpeed(controller.fullSpeed);
        
        ...

Conclusion

And that's it! With just a few lines of HTML, CSS and JavaScript + jQuery, you've created a fully-functional image scroller. If you're imaginative, you'll recognize that this same technique can be used to create many other page features, such as news tickers and more. How will you use the effect on your site?

Thanks to Dan J. for suggesting this article – he will be receiving a $15 Amazon gift certificate as a prize.

Tell Others and Have Your Say

 
 
Customizable Google Maps Made Easy! Try EasyMapBuilder Now »
 
Log In
  Reset Password...
 
Why create an account?
  • Manage support tickets and purchases
  • Access to free extensions
  • Special discounts and offers
  • Access to member-only forums
Create Account
100% Spam-Free Guarantee
(Optional)
 

Use the following form to ask a question or submit a support request. An appropriate staff member will reply as soon as possible (usually within a few hours).
Contact Us / Create Support Ticket
 
To attach files, you must Sign Up or Log In.

You have no items in your basket.  Featured products:

XML Flash Slideshow v4 Flash Audio Kit for Dreamweaver

Home | Customer Satisfaction / Refund Policy | Privacy Policy | jQuery Slider | Top of Page

© 2003-2018 DWUser.com / Magnetic Marketing Corp.  All rights reserved.