jQuery: numbered content slider

A jQuery numbered content slider is a normal content slider which features a progressive numbering at its very bottom indicating the current slide number. When a slide appears, the corresponding number gains a CSS class that highlights it. Implementing this kind of content slider is not very difficult. First, let's start with our markup:

<div id="slider">
 <div id="slider-wrapper">
  <!--slides here-->
 </div>
</div>
<div id="slide-numbers"></div>

The relevant styles for our slide numbers are as follows:

#slide-numbers {
 width: 530px;
 margin: 0 auto;
 padding: 5px 0;
 text-align: center;
}

#slide-numbers span {
 color: #444;
 padding-right: 0.5em;
}

#slide-numbers span.current {
 font-weight: bold;
 color: #d40;
}

The CSS class current will be applied every time a slide comes into view. Of course the first slide is already visible, so we're going to apply this class to it by default. The first thing we need to do with jQuery is to get the left offsets of each slide so that we can use these values later to create our sliding effect:

var getPositions = function() {

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

};

Then we get the current slide number, initialize an internal counter for the slides and populate our slide-numbers element with the appropriate numbers corresponding to the actual slide numbers:


  var len = $('div.slide', '#slider').length;
  var i;
  var index = -1;
  
  for(i = 0; i < len; i += 1) {
  
  
    $('<span></span>').text(i + 1).
    appendTo('#slide-numbers');
  
  
  }
  
  $('span', '#slide-numbers').eq(0).
  addClass('current');

Now we have to create a timer, loop through all slide positions with our internal counter, animate our slider wrapper and add the CSS class current to the corresponding element. Since we want that only a number at time will have such class, we have to remove this class from all of its sibling elements:

 var positions = getPositions();
   
  
  var interval = setInterval(function() {
  
    index++;
    
    if(index == len) {
    
      index = 0;
      
      
    
    
    }
    
    
    
    $('#slider-wrapper').animate({
      left: - positions[index]
    }, 1500, function() {
    
     
    
      $('span', '#slide-numbers').eq(index).
      addClass('current').siblings().removeClass('current');
    
    
    });
  
  
  
  
  }, 1500);

We use our internal counter (index) also to select the current number via the eq() method. You can see the demo below.

Demo

Live demo

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

One thought on “jQuery: numbered content slider”

Leave a Reply

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