jQuery delegate()

The jQuery delegate() method is used to attach a function to run when the event occurs for specified elements which are the children of selected elements, including both the current and the future elements.

Syntax:

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

ChildSelector:

  • It is a mandatory parameter
  • The child selector parameter is used to specify the child elements for a particular event or event.

Event

  • It is also a mandatory parameter.
  • This parameter is used to specify the events to occur.
  • For multiple events selection, events must be separated by space.

Data

  • It is an optional parameter.
  • The data parameter is used to specify any additional data to pass along with the function.

Function:

  • It is an optional parameter.
  • The function parameter specifies the function to run when the event occurs.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
p {
background: turquoise;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<p>This is a single paragraph. Click me for next.</p>
<script>
$( "body" ).delegate( "p", "click", function() {
$(this ).after( "<p>Click me.</p>" );
});
</script>
</body>
</html>