Nick Q. Nick Q. - 5 months ago 15
Javascript Question

Multiple jQuery UI Range Sliders Interacting

I'm creating three separate range sliders with jQuery UI. However, for some reason when moving a handle on a slider the other handle will jump to the position of the corresponding handle on the last slider modified (see gif below). I'd really like to stop this and make the sliders entirely independent.

Broken Sliders

Currently I've only tested it in Chrome.

Here's a JSFiddle that demonstrates the issue. Below is the relevant code:

HTML



<ul id="sliders">
<li id="red">
<div class="slider"></div>
</li>
<li id="green">
<div class="slider"></div>
</li>
<li id="blue">
<div class="slider"></div>
</li>
</ul>‚Äč


Javascript



$( "#sliders .slider" ).slider({
range: true,
orientation: "horizontal",
min: 0,
max: 255,
values: [ 0, 255 ],
slide: function( event, ui ) {
$(this).parent().children(".range").text(ui.values[ 0 ] + " - " + ui.values[ 1 ]);
}
});

Answer

You need to apply the .slider() widget to each item, and not the collection of items.

$( "#sliders .slider" ).each(function(){
    $(this).slider({
        range: true,
        orientation: "horizontal",
        min: 0,
        max: 255,
        values: [ 0, 255 ],
        slide: function( event, ui ) {
            $(this).prev(".range").text(ui.values[ 0 ] + " - " + ui.values[ 1 ]);
        }
    });
});

Also note that you can use .prev() instead of .parent().children()