Computers & ProgrammingFrontend DevelopmentjQuery

jQuery Delegate Event

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)
Parameter Description
childSelector Attach the event handler to one or more specified child elements
event One or more events to attach. Event values are separated by space
data Optional data to pass along to the function
function Function 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. 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();
});

Leave a Comment

Your email address will not be published.

Scroll to Top