Did you find this useful?
Socialize it today.


jQuery Delegate Event

Monday, June 18, 2012

The jQuery event delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. In addition, event handlers that are attached using the jQuery delegate() method will work for both current and future elements. As of jQuery 1.7, the .delegate() method has been superseded by the .on() method. For earlier versions, it remains the most effective means to use event delegation.


Syntax

$(selector).delegate(childSelector,event,data,function)


ParameterDescription
childSelectorAttach the event handler to one or more specified child elements
eventOne or more events to attach. Event values are separated by space
dataOptional data to pass along to the function
functionFunction to run when the event(s) occur


Basic Example

In the following jQuery example, the delegate() method attaches the click event to the element with an id of "imgMouse". When the element is clicked, the specified function will execute. In this example, the div element will be shown or hidden as the mouse icon is clicked. Try it yourself, by clicking the mouse icon. You can copy and edit the jQuery code using our online HTML editor.


<div id="divParent">
    <img id="imgMouse"src="#" />
    <div id="divChild">
    <div id="divText">Click the mouse icon to toggle this display!
         </div>
</div>

$("divParent").delegate("#imgMouse", "click", function () {
    $("#divChild").slideToggle();
     });


mouse
Click the mouse icon to toggle this display!

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual HTML CSS and JavaScript Editor Pro jQuery