.on()
ONLY supports delegation when used with two selectors as in:
$("#parent").on("click", "#child", fn);
The shortcuts like .click()
don't support the two selector syntax and thus don't support delegation in the same way.
In your code examples, these two blocks of code do not have identical behavior:
$("form").on("click", "button", function() {
window.location.href = "submit-page.php";
});
$("button").on("click", function() {
window.location.href = "submit-page.php";
});
The first one uses event delegation and will respond to a propagated event that originated on a "button" object even if that button was added long after the event handler was added. The second is direct event handling only and will only attach event handlers to objects that exist at the time the event handling code is initially run. That's the difference between direct event handling and delegated event handling.
Another subtle difference is that the first one only responds to button
events that are contained within a form
(events propagate up through a form
object) whereas the second one respond to events from any button
in the page that existed at the time the event handler was installed even ones not in a form
.
In your code examples, these two do have the same behavior (both are direct event handlers and will only work on objects that exist at the time the event handler is installed):
$("button").on("click", function() {
window.location.href = "submit-page.php";
});
$("button").click(function() {
window.location.href = "submit-page.php";
});