Mark Bell Mark Bell - 3 months ago 29
Javascript Question

noUiSlider: If I have a slider with two handles, how can I tell which of the handles is being moved?

noUiSlider allows you to create range sliders with multiple draggable handles, as per the snippet below:



var output = $('#output');

$('#range-slider').noUiSlider({
start: [0, 100],
range: {
'min': [0],
'max': [100]
}
}).on('slide', function(evt) {
// In this event handler, I want to see which of the two sliders is being moved
// Is there a property of the 'evt' parameter which would tell me this?
output.html($(this).val().join(' - '));
});

body { padding: 30px 30px; }
#range-slider { width: 300px; }
#output { margin-top: 30px; }

<link href="https://cdn.rawgit.com/leongersen/noUiSlider/c8a70344bebb0b69a09adf12a1e7cc08894f8c3b/distribute/jquery.nouislider.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/leongersen/noUiSlider/c8a70344bebb0b69a09adf12a1e7cc08894f8c3b/distribute/jquery.nouislider.all.min.js"></script>

<div id="range-slider"></div>
<div id="output"></div>





In the event handler for the
slide
event (which is fired continuously as each slider handle is dragged), I want to know which of the handles is currently being moved. I can't see anything in the documentation about this, and inspecting the
evt
parameter of the event handler in a browser's dev tools reveals a mass of data, but none which I can see would identify the handle.

I could do something messy, like binding a
mousedown
event directly to the handle elements and setting the value of a higher-scoped variable which can be accessed from within the event handler to contain the last moved handle ID/class... but I don't really want to, especially if there's a cleaner way. Can anyone help?

Answer

Better handling of this was introduced in this commit, so you now get the handle index as an event callback argument:

$('#range-slider').noUiSlider({
    start: [0, 100], 
    range: {
        'min': [0],
        'max': [100]
    }
}).on('slide', function(values, handle, unencoded, tap, positions) {
    // 'handle' will either be 0 or 1 depending on which handle caused the event to fire
    var whichHandle = handle === 0 ? 'LEFT' : 'RIGHT';
    output.html(values.join(' - '));
});

There is more information about the other callback arguments in the documentation.