The delegate() method attaches one or more event handlers to child elements of specified selector. When selector is provided, the event handler is referred to as delegated. The selector can be button selector which selects elements of type button, checkbox selector which selects elements of type checkbox, child selector which selects child elements specified by parent, element selector which selects all the elements with tag name etc.
It allows attaching single event listener to parent element which will fire for all children matching selector which will work for both current and future elements along with function to perform desired actions. The handler is not called directly when the event occurs, it’s called only when inner elements that match the selector.
JQuery Delegate() Syntax
$(selector).delegate(childSelector, event, data, function)
The delegate() method has following parameters:
- childSelector: It is required parameter. It selects child elements to handle event specified by the parent.
- event: It is required parameter which defines one or more event types such as click, keydown or custom event names to handle event.
- data: It is optional parameter which contains data that will be passed to the event handler.
- function: It is required parameter which executes the function at the time the event is triggered.
JQuery Delegate() Example
<!DOCTYPE html> <head> <meta charset="ISO-8859-1"> <title>Delegate Event</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <script type="text/javascript"> $(document).ready(function() { $("div").delegate("button", "click", function() { $("p").slideToggle(); }); }); </script> <body> <div> <button>Click Delegate Event Run</button> <p>Welcome to JQuery !!!!</p> </div> </body> </html>
- As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
- The line, $(“div”).delegate(“button”, “click”, function() ) uses three parameters namely, button which is child element to handle event, click parameter defines event to handle event and function parameter which executes the function at the time the event is triggered.
- $(“p”).slideToggle() line toggles the element up and down.
- When you execute the program, you will get the button on the output. When you click on the button, delegate event occurs and executes the function when event is triggered. Then element will slide up and slide down using slideToggle() method after clicking on the button.
When you run the above example, you would get the following output: