How can I trigger a change event on a jQuery UI slider?
I thought it would be
$('#slider').trigger('slidechange');
but that does nothing.
Full example script follows:
<link href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
<script src="http://jqueryui.com/latest/ui/ui.core.js" type="text/javascript"></script>
<script src="http://jqueryui.com/latest/ui/ui.slider.js" type="text/javascript"></script>
<body>
<div id="slider"></div>
<script type="text/javascript">
$().ready(function()
{
$('#slider').slider({change: function() { alert(0); }});
// These don't work
$('#slider').trigger('change');
$('#slider').trigger('slidechange');
});
</script>
I would expect this to alert "0" when the page loads
I found it easier to use the 'create' method to call the slide or stop function. Eg, for a slider with a min/max range:
I've hit this problem recently, and used Felipe Castro's comment-solution, with a necessary change to set the context right:
If you bind to to the slider's change event like that:
Then you can trigger it like:
The solution below mentioned by Joey Yore works too, but the downside is that
slidechange
event is not fired (from my experience) when user changes your slider from UI.As documentation;
Just setup bind change event
and set value
Yet another way, which is handy for UI widgets like autocomplete, is to access the event directly via the data method. JQuery stores all of its event hookup info using .data("events"), so if you use that property you can access the events directly. On some UI components (eg. autocomplete) the events aren't even attached to the main element, they're attached to the UI object itself. Luckily, that UI object is also available in data.
So, without further ado, here's how you'd invoke the autocomplete's select event:
Or, (getting back to sliders) to trigger a slider's change:
Trigger is still the best way of course, since it actual utilizes the event system, but on the more complex widgets where "$(elem).trigger" won't be enough, this approach is handy.
* EDIT *
Just figured out that you actually can "trigger" the event properly with this method, using the widget's "secret" _trigger property. For example:
Hope this helps someone.
Try
Not ideal but gets you working!