cycero cycero - 1 year ago 115
jQuery Question

jQuery UI Range Slider - move the right dragger (handle) when clicked in the middle of the slider

I'm using the jQueryUI range slider in the following way:

$(function() {
$( "#slider-range" ).slider({
range: true,
min: 0,
max: 4,
step: 1,
values: [ 0, 4 ],
slide: function( event, ui ) {
$( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
" - $" + $( "#slider-range" ).slider( "values", 1 ) );

What I need to do is - move the right side dragger (handle) to the clicked position when you click in the middle of the slider. Currently, when you click in the middle, the left dragger (handle) is being dragged to that position. Is there a way I can swap that behavior?

Thanks for helping!

Answer Source

That's actually not how it works, although it may appear that way. It actually detects which handle is closest, and choose that one. Each time you click, the distance from BOTH handles, in pixels, is calculated. It's easier to see the functionality with MORE range, see this fiddle I made:

Here is the function jQueryUI uses:

this.handles.each(function( i ) {
var thisDistance = Math.abs( normValue - self.values(i) );
if ( distance > thisDistance ) {
distance = thisDistance;
closestHandle = $( this );
index = i;

source: Line 249 of jquery.ui.slider.js

In general, I think this is usable. Overriding this properly may be a bit difficult because it's inside an anonymous function inside another method which contains a bunch of logic. You COULD, and I really really really don't recommend it, but you COULD modify the source and just set the closest handle to the 2nd. But seriously, don't do that. It's a very bad habbit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download