delegate() Method - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:delegate

jQuery delegate() Method

Description

The delegate() method was deprecated in version 3.0. Use the on() method instead.

The delegate() method attaches one or more event handlers for elements that are children of selected elements for both current and FUTURE added elements.

Syntax

$(selector).delegate(chikldSelector,event,data,function);
Parameter Require Description
childSelector Required. one or more child elements to attach the event handler to
event Required.one or more events to attach to the elements.
data Optional.additional data to pass along to the function
function Required. the function to run when the event occurs

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

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("div").on("click", "button", function(event){
        $(event.delegateTarget).css("background-color", "blue");
    });//www . j  av a2 s.c  o m
});
</script>
</head>
<body>

<div style="background-color:yellow">
  <p>Click the button to change the background color of this div.</p>
  <button>Click me!</button>
</div>

<div style="background-color:yellow">
  <p>Click the button to change the background color of this div.</p>
  <button>Click me!</button>
</div>

<div style="background-color:red">
  <p>Click the button to change the background color of this div.</p>
  <button>Click me!</button>
</div>

</body>
</html>

Related Tutorials