jQuery: basic slideshow

Slideshows are pretty easy to stylize with CSS but somewhat difficult to implement with JavaScript. Fortunately, jQuery makes life easier for us. We can start with a basic unordered list, inserting some images inside the list items and them add some styles to make only the very first image appear on the page. Basically, everything depends on the float and overflow property, as you can see below:

#slideshow {

    width: 100%;
    padding: 0;
    overflow: hidden;
    margin: 0;
    list-style: none;
    height: 327px;
    

}

#slideshow li {

    width: 100%;
    height: 327px;
    float: left;
    

}

#slideshow li img {

    width: 100%;
    height: 100%;
    display: block;

}

Now we have to add the jQuery behavior. Basically, the point is to get a smooth transition effect between each image, and we can use the opacity property for that purpose. Remember that when an image disappears, the other will be revelead thanks to the stack order that we've previously created using floating. Here's the jQuery code:

var $li = $('#slideshow li'), li = 0;

function slideShow() {

            var context = arguments.callee;

    
    
  
  
  
      $($li[li++] || []).animate({
      
         opacity: 'toggle'
      
      }, 4000, context);
  

  


}


$(document).ready(function() {

   slideShow();
     
});

The main function repeats itself by invoking its procedures via the arguments.callee reference. Everything works because we've initialized a counter that automatically will be incremented each time the function runs. You can see the final result here.

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.