jQuery: image carousel tutorial

Creating an image carousel is simple with jQuery. All we need is an image gallery, relative positioning and a JavaScript timer. In this post I'm going to show you how to accomplish this. First of all, we need a basic HTML structure to build our image gallery, like the following:

<div id="gallery">

 <ul>
 
  <li><img src="1.jpg" alt="" />
   <p class="caption">...</p>
  </li>
  
  <!--more items-->
 </ul>
</div>

Each item contains an image and an image caption. Here are our CSS styles:

#gallery {
 padding: 1em 0;
 margin: 0 auto;
 background: #ccc;
 width: 700px;
 overflow: hidden;
}

#gallery ul {
 position: relative;
 margin: 0;
 height: 100%;
 overflow: hidden;
 list-style: none;
 width: 100%;
 padding: 0;
}

#gallery li {
 padding: 0;
 width: 25%;
 float: left;
}

#gallery li img {
 display: block;
 width: 100%;
 height: 120px;
}

#gallery li p.caption {
 margin: 0;
 padding: 5px;
 background: #000;
 color: #fff;
 height: 100%;
 font: small Arial, sans-serif;
 text-align: center;
}

Our list will be moved using relative positioning, so we need to use the overflow property on its parent container to avoid any possible problem due to overflowing content.

Also, our container is 700 pixels wide, so we need to initialize a JavaScript counter that has 700 as its limit value. Then we can use setTimeout() in this way:

$(document).ready(function() {

  var counter = 0;
  
  
  var interval = window.setTimeout(function() {
  
    counter += 1;
    
    $('#gallery ul').css('left', - counter + 'px');
    
    if(counter == 700) {
    
     
      
      counter = 0;

      $('#gallery ul').css({
        left: counter
      });
        
    }
    
    window.setTimeout(arguments.callee, 25);
  
  
  
  
  
  }, 25);


});

The main timer moves our list to the left using negative relative positioning. When our counter has reached the limit (700), we reset the left property of the element. Note that our timer enters in an infinite cycle through this statement:

window.setTimeout(arguments.callee, 25);

This simply means "create another timer by calling again the main timer". In other words, it's simply interval that calls itself. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.