jQuery delegate()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery delegate()

The delegate () method is used to attach one or more event handlers for specified elements which are the children of selected elements. This method executes a function to run when the event occurs.

The attached event handlers with the delegate () method works for both current and future elements.

Syntax:

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

Parameters of jQuery delegate() event

Parameters Description
ChildSelector It is a mandatory parameter that is used to specify one or more child elements to attach the event handler.
Event It is also a mandatory parameter. It specifies one or more events to attach to the elements. If you use multiple events then they must be separated by space.
Data It is optional and specifies additional data to pass along to the function.
Function It is executed when the event occurs.

Let's take a jQuery delegate () example.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>delegate demo</title>  
  6.   <style>  
  7.   p {  
  8.     background: yellow;  
  9.     font-weight: bold;  
  10.     cursor: pointer;  
  11.     padding: 5px;  
  12.   }  
  13.   p.over {  
  14.     background: #ccc;  
  15.   }  
  16.   span {  
  17.     color: red;  
  18.   }  
  19.   </style>  
  20.   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  21. </head>  
  22. <body>  
  23. <p>This is a single paragraph. Click me for next.</p>  
  24. <script>  
  25. $( "body" ).delegate( "p", "click", function() {  
  26.   $(this ).after( "<p>Click me for another paragraph.</p>" );  
  27. });  
  28. </script>  
  29. </body>  
  30. </html>  

Test it Now