3

If we bind a click event to a link as

$("linkSelector").click(function(){ ... });

then we can easily also force executing this event handler even though user didn't click the link.

$("linkSelector").click(function() { ... }).click();

But in my case I'm using jQuery Slider widget which has the slide event to which an event handler can be bound. I wonder how can we force execute its events programatically?

I've tried following but none of them works:

$("sliderSelector").slider({ slide: function(){ ... } }).slide();
$("sliderSelector").slider({ slide: function(){ ... } }).slider("slide");
$("sliderSelector").slider({ slide: function(){ ... } }).trigger("slide");

I know I could use a named function instead of an anonymous one, but I don't consider that a solution because I can call the function with whatever arguments I want while triggering slide event would provide correct values as set by the slider.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • possible duplicate of [Trigger a jQuery UI slider event](http://stackoverflow.com/questions/1288824/trigger-a-jquery-ui-slider-event) – Wayne Weibel Nov 04 '13 at 21:28

2 Answers2

9

Solution

This is the resulting code that actually triggers such event handler:

var s = $("sliderSelector").slider({ slide: function(evt, ui){ ... } });
s.slider("option", "slide").call(s, null, { values: s.slider("values") });

Make sure you provide those function parameters that you actually use in your event handler. In my case where I'm using a range slider I need ui.values parameter, so I'm creating such an object so my handler won't break.

It's not a nice solution since I have to call .slider() function multiple times but it's the safest way of preventing the use of magic values.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
2

I've just had a very similar issue.

If you register your callbacks with .bind() (or .on for later versions of jQuery) instead of putting them into the initialiser you can then invoke them as expected with .trigger().

It seems that the two sorts of handlers are different, but I can't find that documented anywhere.

Alnitak
  • 334,560
  • 70
  • 407
  • 495