jQuery - Event propagation

jQuery

Share

In this tutorial we will learn about event propagation in jQuery.

What is event propagation?

As the name suggests it is a propagation of an event from one element (child) to the next element (parent).

How event propagation occurs?

When an event is fired for a child element it does not stops there but propagates to its parent (ancestor) elements. Its like climbing the DOM tree.

Event bubbling and event propagation are two terms for similar concept.

Example

In the following example we are handling click event for a parent div having id "sample-parent-div" and for a child div having id "sample-child-div".

HTML

<div id="sample-parent-div">
  <p>Parent div</p>
  <div id="sample-child-div">
    <p>Child div</p>
  </div>
</div>

CSS

#sample-parent-div {
  background-color: lightgreen;
  height: 300px;
}

#sample-child-div {
  background-color: lightyellow;
  height: 100px;
}

jQuery

$("#sample-parent-div").on("click", function(){
  console.log("Parent div clicked...");
});

$("#sample-child-div").on("click", function(){
  console.log("Child div clicked...");
});

When the parent div is clicked then in the browser console we get the following output "Parent div clicked...".

But when a child div is clicked we get two outputs "Child div clicked..." and "Parent div clicked...".

This is propagation of event from child element to the parent.

We can prevent this by using the stopPropagation() method.

stopPropagation()

We use the stopPropagation() method to stop the propagation of the event from the child element to the parent elements.

In the following example we have included the stopPropagation() method for the child div. So, when we click the child div we will only get the "Child div clicked..." output.

jQuery

$("#sample-parent-div").on("click", function(){
  console.log("Parent div clicked...");
});

$("#sample-child-div").on("click", function(e){
  console.log("Child div clicked...");
  e.stopPropagation();
});
Share

Recently Added