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.
Solution
This is the resulting code that actually triggers such event handler:
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.valuesparameter, 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.