Search code examples
javascriptjqueryjquery-uianonymous-functionjquery-slider

jQuery UI Slider change and slide events report different results


Okay, so a very similar question was asked here

jQuery UI Slider - Value returned from 'slide' event on release is different from 'change' value

But the answer was unsatisfactory in my opinion. Here is my JavaScript code: http://jsfiddle.net/AsDZJ/4/

function slideVal() {
    var number = $("#number_slider").slider("value");
    $("#number_field").append('Slide: ' + number + '<br/>');
}

function changeVal() {
    var number = $("#number_slider").slider("value");
    $("#number_field").append('Change: ' + number + '<br/>');
}

$(function() {
    $( "#number_slider" ).slider({
        min: 1,
        max: 10,
        change: changeVal,
        slide: slideVal
    });

    $( "#number_slider" ).slider( "value", 5 );
});

The issue is that the slider is reporting different values between when the change handler is called, and when the slide handler is called.

Now, the other question points out that if you declare the function anonymously, you can simply use ui.value, like so:

$( "#number_slider" ).slider({
    min: 1,
    max: 10,
    change: function(event, ui) {
        $("#number_field").append('Change: ' + ui.value + '<br/>');
    }
});

This does give more consistent results, but also means that if, as in my case, I have a lot of complex logic to perform whenever the event changes, I have to repeat code. In addition, the calculations involve slider values from multiple sliders.

How can I get access to the correct value from an explicitly declared function? Is this behavior in jQuery UI a bug?

Thanks


Solution

  • You can still define global functions with parameters, when you initialize the slider just pass in the function name instead of using an anonymous callbacks

    function slideVal(e, ui) {
        var number = ui.value;
        $("#number_field").append('Slide: ' + number + '<br/>');
    }
    
    function changeVal(e, ui) {
        var number = ui.value;
        $("#number_field").append('Change: ' + number + '<br/>');
    }
    
    $(function() {
        $( "#number_slider" ).slider({
            min: 1,
            max: 10,
            change: changeVal,
            slide: slideVal
        });
    
        $( "#number_slider" ).slider( "value", 5 );
    });