Search code examples
jqueryjquery-uijquery-eventstogglebutton

jQuery UI toggle button events


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

Solution

  • 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)