Nov 10, 2018

What is event bubbling or event propagation

Let us say you have a link <a> inside a <div> as shown here:

<div id="div88">
    <a href="#" id="a88">Click here</a>
</div>
The click event is hooked on both the link and the div:

$("#div88").click(function (e) {
    alert("div clicked");
});

$("a").click(function (e) {
    alert("link clicked");
});

When you click the link, the click() event fires and a function runs which displays "link clicked" in an alert box. The event however, doesn't stop there. You will see another alert box which says "div clicked". In other words, even though you clicked the <a>, the <div> being its ancestor element, also receives the click event. This is called event bubbling or event propagation.

If you want to stop the event from bubbling, you can use stopPropagation:

$("a").click(function (e) {
    alert("link clicked");
    e.stopPropagation();
});