×

jQuery Tutorial

jQuery Examples

jQuery Practice

jQuery delegate() Method

jQuery | delegate() Method: Learn about the jQuery delegate() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 27, 2022

delegate() Method

Events in jQuery are the actions that the user performs on the web page. It can be anything – related to mouse clicks, keyboard presses, etc. Using jQuery, we can control these events in the order we want and can also attach some custom functions to it if needed. That means, we can use predefined event methods for the actions and also define a function that gets fired when the event method is triggered. Overall, this makes the website more dynamic on the user's end. Let's learn about the delegate() method here.

The delegate() method is a built-in jQuery method. The delegate event helps to attach an event handler to the children of the selected element. When a similar task has to be performed on all of the child elements, then the delegate event is useful which triggers the delegate() method.

delegate() Method Syntax

$('selector').delegate('childElement','event',function(){});

This method takes three required parameters – child element, event name, and function.

The child element name has to be specified in order to target those special elements. It can be specified using tag name, class, id, etc. The event name has to be given in order to trigger the function when the specified event occurs by the user on the selected parent element. The function is the action that is executed once the specified event is triggered.

This method can be implemented even if some of the child elements are not created at present but can be created in the future.

Note: The delegate event has been deprecated in version 3.0. Therefore, now we use the .on() method to perform the required task.

jQuery delegate() Method Example

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <h2>jQuery Event - Delegate</h2>
    <hr>
    <div class="parent">
      This is Parent Class.
      <div class="child"><br>- This is a Child Class - One</div>
      <div class="child">- This is Child Class - Two</div>
    </div>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('div.parent').delegate('div.child','click',function(){
            $('div').css({'color':'teal', 'font-size':'x-large'});
        })
    });  
  </script>
</html>

Output:

Example 1: jQuery delegate() Method


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.