55

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

William Perron
  • 485
  • 7
  • 16
Greg
  • 316,276
  • 54
  • 369
  • 333

12 Answers12

51

Try

$slider = $('#slider');
$slider.slider('option', 'change').call($slider);

Not ideal but gets you working!

alt text

Vikrant
  • 4,920
  • 17
  • 48
  • 72
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 3
    Eww ugly :p +1 though 'cause it works. I'll give it a bit longer in case John Resig stops by... – Greg Aug 17 '09 at 17:49
  • hmm, not sure he will know. Maybe better as a jquery-ui google group post / trac issue. Not sure if they considered this used case? – redsquare Aug 17 '09 at 17:50
  • I've edited your answer because while it worked for my test script it didn't work for the real one - "this" was coming out wrong. – Greg Aug 18 '09 at 08:08
  • 1
    This is not a solution. Calling the function associated with the event is not the same as triggering the event itself, e.g. you have to manually pass the parameters (even if this case it's only the object, other events may have more parameters) – Patonza May 12 '10 at 15:51
  • 1
    $slider.slider('option', 'change') returns $slider object not a function – Eugene Gluhotorenko Jul 20 '12 at 12:56
  • 8
    @redsquare When i try to trigger "slide" event with $slider.slider('option', 'slide').call($slider); I get "event" and "ui" undefined. – SUN Jiangong Oct 05 '12 at 09:20
  • How ui and event are initialised? – sites Mar 22 '13 at 16:51
  • 15
    @charlessun I had the same problem, and got it working providing those two params manually: `$slider.slider('option', 'slide')(null, { value: $slider.slider('value') })` (first param is 'event' and second is 'ui'). Jquery UI version 1.10.2 – Felipe Castro Apr 22 '13 at 19:27
  • 4
    Seriously, jqueryUI is such a complete mess, anything slightly advanced and you're resorted to hacks. Not only slider either - the whole library is consistently shitty. – raveren Jul 02 '13 at 05:22
  • 1
    @Raveren - Then don't use it - make one yourself. – Adrian Bartholomew Sep 27 '13 at 12:14
  • 1
    I no longer do, I've resorted to single-serving libraries that just work. – raveren Sep 27 '13 at 13:12
  • 1
    If its a multi handle slider use this instead: $slider.slider('option', 'slide')(null, { values: $slider.slider('values')}) – radtek Jun 23 '14 at 15:53
  • @Felipe Castro. Maybe you should post this as a separate answer as it was the solution in my case. – john-jones May 17 '16 at 14:01
40

I know this is way past the post date, but I wanted to post to provide this solution to anyone that stumbles upon this post.

You can accomplish event triggering by doing something along the lines of:

//TO DEFINE SLIDER AND EVENTS
$('#slider').slider().bind('slidechange',function(event,ui){...});

//TO TRIGGER EVENT
$('#slider').trigger('slidechange');

Unfortunately you cannot define the functions as options within the init object, however, I think it ends up looking cleaner and is more straight forward and correct than the other answer using the call method (i.e. it does use the event system).

And yes, the callbacks you define here will be called on normal operation (changing the position of the slider in this case) as it normally would. Just make sure you use the correct event type names from the UI documentation.

If you want to add multiple events at once, remember you can provide an object to bind using the event names as keys:

//TO DEFINE SLIDER AND EVENTS
$('#slider').slider().bind({
    slidestart  : function(event,ui) {...},
    slidechange : function(event,ui) {...},
    slidestop   : function(event,ui) {...},
});

//TO TRIGGER EVENTS
$('#slider').trigger('slidestart');
$('#slider').trigger('slidechange');
$('#slider').trigger('slidestop');

This is noted in the documentation, although, it is not very clear. Took me developing a couple plugins on my own to really understand the UI event system.

Enjoy

Joey Yore
  • 411
  • 4
  • 5
18

A good approach is simply to change the value of the slider. The slider's own change method should then respond to the change of value. For instance:

var newValue=5;
$('#slider').slider("value", newValue);
hrabinowitz
  • 1,600
  • 2
  • 13
  • 12
  • I'd say this should be the correct answer. I can't think of a use case where it is imperative that you trigger an event without changing the value of the slider. Let the slider dispatch the events as they were defined when it was constructed. – Alex. P. Feb 19 '16 at 15:18
  • I have such a case. I'm dynamically changing the colour of optional grid lines on an image with a slider. The grid lines and slider disappear if I untick a checkbox for the grid lines option. I want the change event on the slider to fire to to redraw the lines if I tick that checkbox to re-show grid lines, but I want the last colour chosen. Luckily, the change event still fires even if you set the value to itself, although the code is really ugly: `$('#slider').slider('value', $('#slider').slider('value'));` ) – Lisa DeBruine Feb 12 '17 at 19:47
4

This maybe resurrecting an old thread, but was just having a similar experience. The solution that I came up with (because the thought of calling slider(...) multiple times was not appealing):

$slider.slider('option', 'slide').call($slider, event, ui);

With $slider being bound to the $(selector).slider(...) initialization.

Wayne Weibel
  • 933
  • 1
  • 14
  • 22
  • 1
    The approach you've mentioned works for me, as does that of Felipe Castro. But I don't understand why I cannot just say `$slider.trigger("slide", ui);` – hrabinowitz Nov 08 '13 at 22:45
  • I continued to play around with it all and the only explanation I could see was that the 'slide' event was not on the $slider object, but rather an element of $slider (if that makes sense). You first had to retrieve the desired function of the 'slider' (not $slider) object then call it with the appropriate parameters. The 'slider' is actually several DOM elements so there is not a true trigger point for the function. – Wayne Weibel Nov 12 '13 at 20:24
4

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:

$("#autoComplete").data("autocomplete").menu.select()

Or, (getting back to sliders) to trigger a slider's change:

$("#slider").data("slider")._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:

$("#autoComplete").data("autocomplete")._trigger("select", fakeEvent, fakeItem)

Hope this helps someone.

Alp
  • 29,274
  • 27
  • 120
  • 198
machineghost
  • 33,529
  • 30
  • 159
  • 234
2

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:

$('#height').slider({
        ...
        create: function(event, slider){ $( "#height" ).slider( "option", "values", [1100, 1500] ); handleHeightSlide('slide', $( "#height" ));},
        ...
    });
2

Wanted to add a comment on Joey Yore's answer -

I think it's better the other way round

$('#slider').bind({
    slidestart  : function(event,ui) {...},
    slidechange : function(event,ui) {...},
    slidestop   : function(event,ui) {...},
    slidecreate : function(event,ui) {...}
}).slider();

Otherwise some events (namely, 'slidecreate') will be ignored

gotofritz
  • 3,341
  • 1
  • 31
  • 47
1

As documentation;

change( event, ui ) Triggered after the user slides a handle, if the value has changed; or if the value is changed programmatically via the value method.

Just setup bind change event

$(".selector").slider({change: function(event, ui) {console.log('It Works!'}});

and set value

$(".selector").slider('value',0);
rbostan
  • 37
  • 5
0

I Used both slidechanged and slide, slide triggers when drag the point, slidechanged triggers after release the mouse button (just like click event)

var slider1 = $("#slider1").slider({ min: 1, max: 6 });
//option 1
slider1.on("slide", function (e, ui) {

});
//Option 2
slider1.on("slidechanged", function (e, ui) {

});
Premila
  • 15
  • 5
0

I've hit this problem recently, and used Felipe Castro's comment-solution, with a necessary change to set the context right:

$slider.slider('option', 'slide').apply($slider, [null, {value: $slider.slider('value')}])
niquis7
  • 1
  • 1
  • 1
-1

If you bind to to the slider's change event like that:

$('#slider').change(function() {
    alert('action');
});

Then you can trigger it like:

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

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.

//TO DEFINE SLIDER AND EVENTS
$('#slider').slider().bind('slidechange',function(event,ui){...});

//TO TRIGGER EVENT
$('#slider').trigger('slidechange');
Nikolai Samteladze
  • 7,699
  • 6
  • 44
  • 70
-1

The jQueryUI Slider documentation gives the following example for triggering an event:

$( ".selector" ).slider({
    change: function( event, ui ) {}
});

and for the event trigger:

$( ".selector" ).on( "slidechange", function( event, ui ) {} );

this didn't work for me!

All I had to do to get it working was to change "slidechange" to "change".

$( ".selector" ).on( "change", function( event, ui ) {} );

Hope this helps the future generations that stumbleupon this problem.

Joe Black
  • 393
  • 1
  • 6
  • 10