Description: Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
As of jQuery 1.7, .delegate() has been superseded by the .on() method. For earlier versions, however, it remains the most effective means to use event delegation. More information on event binding and delegation is in the .on() method. In general, these are the equivalent templates for the two methods:
// jQuery 1.4.3+
$( elements ).delegate( selector, events, data, handler );
// jQuery 1.7+
$( elements ).on( events, selector, data, handler );
For example, the following .delegate() code:
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
is equivalent to the following code written using .on():
$( "table" ).on( "click", "td", function() {
$( this ).toggleClass( "chosen" );
});
To remove events attached with delegate(), see the .undelegate() method.
Passing and handling event data works the same way as it does for .on().
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
p {
background: yellow;
font-weight: bold;
cursor: pointer;
padding: 5px;
}
p.over {
background: #ccc;
}
span {
color: red;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$( "body" ).delegate( "p", "click", function() {
$( this ).after( "<p>Another paragraph!</p>" );
});
</script>
</body>
</html>
$( "body" ).delegate( "p", "click", function() {
alert( $( this ).text() );
});
$( "body" ).delegate( "a", "click", function() {
return false;
});
$( "body" ).delegate( "a", "click", function( event ) {
event.preventDefault();
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$( "body" ).delegate( "p", "myCustomEvent", function( e, myName, myValue ) {
$( this ).text( "Hi there!" );
$( "span" )
.stop()
.css( "opacity", 1 )
.text( "myName = " + myName )
.fadeIn( 30 )
.fadeOut( 1000 );
});
$( "button" ).click(function() {
$( "p" ).trigger( "myCustomEvent" );
});
</script>
</body>
</html>