Richard Parnaby-King

jQuery UI Slider Legend Under Slider

jQuery UI Slider makes selected elements into sliders. There are various options such as multiple handles, and ranges. The handle can be moved with the mouse or the arrow keys.

It is possible to control a select element, showing the options as the slider is moved. But what happens if the options are not as simple or predictable as 1, 2, 3,..?

For example, if a select element is describing cars then only showing the currently selected option is not very user friendly. What you need to do is show each option below where the slider will stop.

The Slider

This jQuery will create a slider after our select element, then when the user moves the slider, the value of the current option will be placed into the anchor tag that is acting as the slider control.
[javascript]
$(function(){
//select element 2+ options
var el = $(‘.select’);

//add slider
var slider = $( ‘

‘ ).insertAfter( el ).slider({
min: 1,
max: el.options.length,
range: ‘min’,
value: el.selectedIndex + 1,
slide: function( event, ui ) {
el.selectedIndex = ui.value – 1;
slider.find(“a”).text(el.options[el.selectedIndex].label);
}
});

//pre-populate value into slider handle.
slider.find(“a”).text(el.options[el.selectedIndex].label);
)};
[/javascript]

Solution

To create a legend, we need to know the width of the slider and the number of elements then divide one against the other:

[javascript]
//store our select options in an array so we can call join(delimiter) on them
var options = [];
for each(var option in el.options)
{
options.push(option.label);
}

//how far apart each option label should appear
var width = slider.width() / (options.length – 1);

//after the slider create a containing div with p tags of a set width.
slider.after(‘

‘ + options.join(‘

‘) +’

‘);
[/javascript]

The p tag needs to have the style ‘display:inline-block’ to render correctly, otherwise each label will take one line or the labels will be stacked up right next to each other.

Using some clever CSS we can then style our slider handle, or we can cheat and just use a background image ;)