jQuery UI image slideshow

Creating an image slideshow with jQuery UI is easy, because this framework provides the slider() component which handles everything automatically. In this post I'm going to show you how to accomplish this using the aforementioned jQuery UI component. As always, let's start with our basic markup first.

<div id="slider">

 <div id="slider-wrapper">
 
   <!--images here-->
 
 </div>
</div>

<div id="slider-controls"></div>

Our slider controls have been intentionally left empty because they will be later filled by jQuery UI. Now our CSS styles:

#slider {
 width: 400px;
 height: 300px;
 position: relative;
 overflow: hidden;
 margin: 0 auto;
}

#slider-wrapper {
 width: 2000px;
 height: 300px;
 position: relative;
}

#slider-wrapper img {
 float: left;
 width: 400px;
 height: 300px;
}

#slider-controls {
 width: 300px;
 margin: 10px auto;
}

With jQuery, we first need to create a function that will store in an array all the left offsets of the images:

var getPositions = function() {

  var positions = [];
  
  $('img', '#slider-wrapper').each(function(i) {
  
    var left = $(this).position().left;
    
    positions[i] = left;
  
  
  });

  return positions;
};

Then we need to initialize an internal counter among with other default variables:

var img = $('img', '#slider-wrapper');
var index = 0;
var len = img.length;
var pos = getPositions();

pos is an array containing all the image offsets, len is the number of images in our slideshow and index is our internal counter. We need to increment our internal counter every time a user activates our slider control in order to make our slider wrapper show the current image using the newly created array. We attach this function to the slide callback method of our jQuery UI slider, also providing minimum and maximum values for the range used by jQuery UI:

$('#slider-controls').slider({
    min: 0,
    max: len,
    slide: function(event, ui) {
    
      index++;
      
      if(index == len) {
      
        index = 0;
      
      
      }
      
      $('#slider-wrapper').animate({
        left: - pos[index]
        
      }, 500);
    
    }
});

That's it. You can see the demo below.

Demo

Live demo

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

One thought on “jQuery UI image slideshow”

Leave a Reply

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