Search code examples
jqueryjquery-uijquery-ui-slider

jQuery UI Slider Labels Under Slider


I am limited to using jQuery 1.4.2 and jQuery ui 1.8.5 (this is not by choice, please do not ask me to upgrade to latest versions). I have created a slider that shows the current value above the slide bar, but what I need now is a way to populate a legend below the slide bar distanced the same as the slider (i.e. if the slider is 100px wide and there are five values the slider will snap every 20px. In this example, I would like the values in the legend to be placed at 20px intervals).

Here is an example of what I want:

Slider

Here is the jQuery I have (assimilated from the ui slider demo page):

//select element with 5 - 20 options
var el = $('.select');

//add slider
var slider = $( '<div class="slider"></div>' ).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);
    },
    stop: function() {
      $(el).change();
    }
});

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

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:

    //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('<div class="ui-slider-legend"><p style="width:' + width + 'px;">' + options.join('</p><p style="width:' + width + 'px;">') +'</p></div>');
    

    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.

    I have created a post explaining the problem and solution: jQuery UI Slider Legend Under Slider which contains a live demo of this working.