jQuery: a slider with a select box

A slider built with a select box is simply a normal slider where slides are selected through the values associated with each option element. All you have to do is to remember that the change event is related to the select element, not to its options. In the following example, each option has an anchor as its value that points to the corresponding slide to be animated. All we have to do is simply to select the correct option element.

Thankfully, each select box has a selectedIndex property associated with it that tells us which value has been selected. As with arrays, this property starts from zero. In our case, we have the following structure created with jQuery:

<select id="nav" name="nav">

 <option>Navigate</option>
 <option value="#slide-1">Slide 1</option>
 <option value="#slide-2">Slide 2</option>
 <option value="#slide-3">Slide 3</option>

</select>

The first option box has no value, so we're not interested in it. We can select each option element using the selectedIndex property combined with the jQuery eq() method:

$('#nav').change(function() {
  
    var index = $(this)[0].selectedIndex;
    var ref = $(this).find('option').
              eq(index).attr('value');
              
    $(ref).show().
    animate({
      left: 0
    }, 'fast').
    siblings().
    hide().
    css('left', '-1000em');
    
    
      
});

The value attribute of each option element (except the first one) contains an anchor that points to a single slide on the page. We pass this value to the $() wrapper so that we can animate and show the selected slide. You can see the demo below.

Demo

Live demo

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

One thought on “jQuery: a slider with a select box”

Leave a Reply

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