jQuery slider “change” event: How do I determine who called it?
Asked Answered
D

1

7

I got a slider that is used as a time-line in my music player. The min value is 0 and the max vlaue is the song length (in seconds). Each second (I do this with a timer), the slider moves and the value is set to the current time. This code line looks like that:

$("#sliderTime").slider("option", "value", document.sound.controls.currentPosition);

The user is able to slide/click the slider and jump to another point in the song, this is by firing the function 'play(startPlayFromHere)'. It looks like that:

$("#sliderTime").slider({
   ...
  change: function (event, ui) { play(ui.value) },
});

The problem is that both the code line in the timer and the user are calling the same 'change' event of the the slider, and the user can't move the slider.

So my question is how can I determine whether the user called the change event or not (that means it was the timer)?

I hope it's clear enough, Thanks!

Digitigrade answered 21/4, 2012 at 0:14 Comment(0)
E
23

You can determine whether a change event arose manually or programmatically by testing event.originalEvent in the change handler.

$('#slider').slider({
    change: function(event, ui) {
        if (event.originalEvent) {
            //manual change
            play(ui.value);
        }
        else {
            //programmatic change
        }
    }
});

See fiddle.

Erie answered 21/4, 2012 at 3:5 Comment(2)
Thanks! Now I got another issue: When the user tries to slide, the timer still works and slides the slider. So sometimes the slider goes back to the original position and ignores the users's call.Digitigrade
No time to write it but you can attach a start handler (see documentation) to raise a flag which will inhibit (with corresponding adjustment of the timer code) the timer's control of the slider. Re-lower the flag in the change handler. (Alternatively, stop the timer, then restart it).Erie

© 2022 - 2024 — McMap. All rights reserved.