jQuery: content slider with the ScrollTo plugin

With the aid of the jQuery's ScrollTo plugin we can actually create a content slider that simply works really smoothly. There's nothing different from other content slider examples, except that we're going to use scrollTo() to make everything work. First of all, let's start with our usual markup:

<div id="wrapper">
  <div id="slide-wrapper">
 <div class="slide">1</div>
 <!--other slides-->
  </div>
</div>

Our CSS styles are exactly the same as in many other content sliders:

#wrapper {
 width: 400px;
 height: 300px;
 position: relative;
 margin: 2em auto;
 overflow: hidden;
 clear: both;
 cursor: pointer;
}

#slide-wrapper {
 width: 2000px;
 height: 300px;
 overflow: hidden;
 position: relative;
}

div.slide {
 width: 400px;
 height: 300px;
 line-height: 300px;
 font-size: 2em;
 text-align: center;
 background: silver;
 float: left;
 position: relative;
}

With jQuery we need to store all the left offsets of the slides into an array for using them later with ScrollTo:

var getPositions = function() {

  var offsets = [];
  
  $('div.slide', '#slide-wrapper').each(function(i) {
  
    var left = $(this).position().left;
    
    offsets[i] = left;
  
  
  });
  
  return offsets;

};

Then we have to create an index to access our array values (this will be incremented each time we click on the slider wrapper) and a limit value, which in our case is simply the number of our slides. Finally, we can use slideTo():

$(function() {

  var pos = getPositions();
  var len = $('div.slide', '#slide-wrapper').length;
  
  
  var index = 0;
  
  $('#wrapper').click(function() {
  
    index++;
    
    if(index == len) {
    
      index = 0;
      
    }
    
        
    $(this).scrollTo(pos[index], {duration: 800, axis: 'x'});
      
  
  
  });


});

We pass a duration and axis parameters to ScrollTo in order to specify the animation speed and the direction of the animation, which in this case is horizontal. You can see the 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.