Why doesn't $("#slider").trigger("slide") result in calling the slide handler?

11,599

Solution 1

Working demo: http://jsfiddle.net/fLnmN/ or http://jsfiddle.net/F5ZCK/

Use .bind like I used in the demo. you can use .on as well like this: http://jsfiddle.net/u82Y5/

Some really helpful post here: Trigger a jQuery UI slider event

This should fit your need, :)

code

$('.slider').slider().bind({
    change: function() {
       alert('change triggered');
    }
});

$('.slider').trigger('change');

OR

$('.slider').slider().on({
    change: function() {
       alert('change triggered');
    },
    slidechange: function() {
        alert('slide trigger');
    }
});

$('.slider').trigger('change');
$('.slider').trigger('slidechange');

Solution 2

The reason trigger('slide') doesn't work is because when you set your slide callback, the slider does not register a slide event with the DOM element. Instead, it delegates generic mouse events to the DOM element and then translates them into your callbacks internally.

Unfortunately, this leaves you to work around that API. Tats_innit's answer binds events directly to the DOM element, but they don't tie into the slider API. You'll have to call your callback function within these handler function.

If you have your callbacks accessible, you can call them directly, as follows:

$('#slider').slider({
  'slide': onSlide
}).on('slide', onSlide);

If you prefer to define the callback functions inline, you can retrieve them as follows:

$('#slider').slider({
  'slide': function(event, ui) { /* ... */ },
}).on('slide', function() {
  $(this).slider('option', 'slide').apply(this, arguments);
});

Needless to say this is painfully redundant, but again, it's a workaround.

On a side note, remember that triggering events individually skips over other events that would be called in succession when they come from the user. For example, triggering a stop event would miss the slide event that the user would generate as he is adjusting the slider. You might consider "justifying" the external event binding by creating a custom event that dispatches multiple events on your behalf (e.g., $('#slider').trigger('setvalue')).

Share:
11,599

Related videos on Youtube

kjo
Author by

kjo

Updated on September 16, 2022

Comments

  • kjo
    kjo over 1 year

    I have a jQuery slider (actually, a custom extension thereof) equipped with a handler for the slide event, and this handler gets properly called when the slider is manipulated interactively, but not when I run

    $("#slider").trigger("slide");
    

    This command runs without error, but the slide handler does not get called.

    Why is this?

    Do I need to pass a different argument to trigger to cause the slide handler to be called?

    EDIT: changed post's title to more closely reflect the question's motivation.