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.
selectorA selector to filter the elements that trigger the event.
eventTypeA string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
handlerA function to execute at the time the event is triggered.
selectorA selector to filter the elements that trigger the event.
eventTypeA string containing one or more space-separated JavaScript event types, such as "click" or "keydown," or custom event names.
eventDataA map of data that will be passed to the event handler.
handlerA function to execute at the time the event is triggered.
Delegate is an alternative to using the .live() method, allowing for each binding of event delegation to specific DOM elements. For example the following delegate code:
$("table").delegate("td", "hover", function(){ $(this).toggleClass("hover"); });
Is equivalent to the following code written using .live()
:
$("table").each(function(){ $("td", this).live("hover", function(){ $(this).toggleClass("hover"); }); });
See also the .undelegate() method for a way of removing event handlers added in .delegate().
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
<script src="https://code.jquery.com/jquery-latest.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>
<head>
<style>
p { color:red; }
span { color:blue; }
</style>
<script src="https://code.jquery.com/jquery-latest.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>