jQuery: infinite carousel

jQuery: infinite carousel

Creating an infinite, cyclic carousel with jQuery.

An infinite carousel created with jQuery is made up of two components: the CSS rules that make the main container as large as needed and the jQuery code that cyclically makes the carousel container slide. What we'll see below is the result of the aforementioned combination of CSS and jQuery.

HTML

The underlying structure is pretty simple:

<div id="carousel-container">
    <div id="carousel-inner">
        <ul id="carousel-ul">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>                  
        </ul>
    </div>
</div>​

Only our list will be large enough to host an almost infinite number of items.

CSS

Here's our CSS code:

#carousel-container {
    width: 680px;
    margin: 2em auto;
    position: relative;
    border: 1px solid #ccc;
    overflow: hidden;
    height: 250px;
}

#carousel-inner {
    width: 680px;
    float: left;
    position: relative;
    overflow: hidden;
}

#carousel-ul {
    position:relative;
    left:-160px;
    list-style-type: none;
    margin: 0px;
    padding: 0px;
    width:9999px;
    padding-bottom:50px;
}

#carousel-ul li{
    float: left;                                    
    width: 150px;  
    padding:0px;
    height:186px;
    margin: 50px 15px 0 15px;
    position: relative;
    background: #c0c0c0;
    line-height: 186px;
    font-size: 2em;
    text-align: center;
}
​

As you can see, our list is 9999 pixels wide but only 680 pixels are visible thanks to the overflow property set on its parents. Further, our list has been initially shifted to the left by a negative value which is equal to the overall width of each item.

jQuery

The core of our carousel is entirely contained in the following function:

var sliding = function() {


       
        var item_width = $('#carousel-ul li').outerWidth() + 10;

        
        var left_indent = parseInt($('#carousel-ul').css('left')) - item_width;

        
        $('#carousel-ul:not(:animated)').animate({
            'left': left_indent
        }, 2000, 'linear', function() {

            
            $('#carousel-ul li:last').after($('#carousel-ul li:first'));

            
            $('#carousel-ul').css({
                'left': '-160px'
            });
        });




};

First, we get the actual width of each item. Then we subtract the left offset of the list from the width of each item in order to get a value that we'll use to make the carousel slide. When the sliding is complete, we move the last item just after the first one to create the effect of an infinite, ciclic movement. Finally, we restore the original left offset of our list.

You can see the complete code and the demo below.

Demo

Live demo