views:

62

answers:

1

How do I bind events to a jQuery UI Toggle button? More specifically, how can I bind events that are going to fire?

The checkboxes are rendering to toggle buttons correctly, but any event handlers attached to them are not triggered when the state of the button changes. Is there something I'm missing?

CSS:

<input type='checkbox' id='recording'/> <label for='recording'> Recording </label>

JavaScript:

$('#recording').button() // works
    .click(fn)           // doesnt work
    .changed(fn)         // doesnt work
    .toggle(fn, fn2)     // doesn't work
+1  A: 

Assuming that there's nothing particularly odd about the jQuery-UI toggle buttons:

$('#recording').live('click',
function() {
// the stuff you want to do when the future-created buttons are clicked
});

Documentation, from http://api.jquery.com/, on the live event-handler.

In place of 'click' you can also use:

  • (jQuery 1.3.x) 'dblclick', 'keydown', 'keypress', 'keyup', 'mousedown', 'mousemove', 'mouseout', 'mouseover' and 'mouseup'
  • (jQuery 1.4.1) all the above, plus: 'focus', 'blur' and 'hover'.

See the http://api.jquery.com/live/ reference for full details.

As @Peter Ajtai noted (in comments):

If you list all the events you can bind, you should also list custom events and that you can include multiple events by leaving a space between each pair of events.

(Emphasis mine)

David Thomas
Surprisingly, this works. But binding a click directly does not, what a joke. Thank you muchly sir, you've saved a perfectly (reasonably) good keyboards life today.
Josh Smeaton
Or you can use [ **`.delegate()`** ](http://api.jquery.com/delegate/) which may offer some added flexibility in certain situations.
Peter Ajtai
@Peter, yup. I never thought to mention that. +1, sir! =) @Josh, any day in which I save a (reasonably) good keyboard's life is a good day. =b
David Thomas
@David - If you list all the events you can bind, you should also list custom events and that you can include multiple events by leaving a space between each pair of events.
Peter Ajtai