jQuery Introduction | Event Handling | Event Delegation event.preventDefault()
Event Delegation
Through event delegation, jQuery allows an event handler that applies commonly to many elements to work with just one binding on a common parent element.
The following example attaches a click event handler to multiple <a> elements.
$("#linkList a").on("click", function(event) {
event.preventDefault();
alert("This link does not work!");
});
<ul id="linkList">
<li><a href="//www.devkuma.com">First link</a></li>
<li><a href="//www.devkuma.com">Second link</a></li>
</ul>
In this case, the event handler attached to each element is connected to the <a> elements that currently exist on the screen, but not to elements added later.
Let us add a button that adds a new element in the example above.
$("button").one("click", function() {
$("#linkList").append('<li><a href="//www.devkuma.com">New link</a></li>');
});
<button>Add new link</button>
In this situation, if you use event delegation, the newly added <a> element can also be connected.
$("#linkList").on("click", "a", function(event) {
event.preventDefault();
alert("This link does not work!");
});
When the event passed as the first argument is propagated to the relevant element, the .on() method checks whether the element that generated the event matches the selector passed as the second argument. If the element where the event occurred matches the selector passed as the second argument, the connected event handler is executed.
With event delegation, not only child elements that currently exist, but also newly added child elements, are connected automatically.
Event Propagation
Event propagation is the process by which the browser decides which target element should execute an event handler when an event occurs. When an event occurs on the Document object or on an element of an HTML document, event propagation occurs to determine the target object. This propagation process is called event bubbling.
Event bubbling means the process in which an event starts from the element where it occurred and propagates upward along the DOM tree. In other words, after the event handler connected to the element where the event occurred is executed, the handler connected to its parent element is executed. Then the handler registered on that parent element’s parent is executed, and the propagation continues up to the Document object.
This propagation makes event delegation possible.
For more details about event propagation, see the JavaScript lesson on event listener invocation.