2

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

Community
  • 1
  • 1
Sibicle
  • 41
  • 1
  • 6
  • Well, here is one solution. It seems pretty stupid to me, perhaps someone can provide a better answer. I set some variables available to both scopes. Inside the anonymous event handler function I first set the appropriate 'global' variable using `ui.value`, then call the function that handles the calculation logic. http://jsfiddle.net/AsDZJ/6/ – Sibicle Apr 16 '13 at 05:06
  • Hi, i don't know if this will help but have you try use stop event and cross the results with the change event. I am saying this because final value in change should be the stop event value not the slide event, i think. – joao May 16 '13 at 09:40

1 Answers1

0

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 );
});
Ant
  • 336
  • 1
  • 3
  • 14