jQuery delegate()

Introduction

When a <p> element inside a <div> element is clicked, change the background color of all <p> elements:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>// w w  w.ja v  a2  s .  c om
<script>
$(document).ready(function(){
  $("div").delegate("p", "click",function(){
    $("p").css("background-color", "red");
  });
});
</script>
</head>
<body>

<div style="background-color:yellow;">
  <p>This is a paragraph inside a div element.</p>
</div>

<p>This is a paragraph.</p>

</body>
</html>

The delegate() method was deprecated in version 3.0.

Use the on() method instead.

The delegate() method attaches one or more event handlers for specified elements' children.

It sets a function to run when the events occur.

Event handlers attached using the delegate() method will work for both current and future elements.

$(selector).delegate(child_Selector,event,data,function)
Parameter
Optional
Description
child_Selector
Required.
one or more child elements to attach the event handler to
event


Required.


one or more events to attach to the elements.
Multiple event values are separated by space.
Must be a valid event
data
Optional.
additional data to pass to the function
function
Required.
function to run when the event occurs



PreviousNext

Related