Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 19, 2021 03:09 am GMT

What is Event Bubbling in JavaScript?

This post will reveal the mystery of button, how it works when you click it. Let's learn about Event Bubbling in JavaScript.

What does it Mean?

Whenever an event is started, it goes form the deeply nested element to all way up to its ancestors' element to up to its ancestors which lie on top of it.

What are events?

An event is something which makes our JavaScript interact with the HTML page. Just like the "onClick" event of a button.

The element which triggers the event is called "target" ad can be accessed using "event.target()". The current element on which the handler currently runs can be accessed using "this" inside the handler function. Eg:

<div id ="parent">    <button id="child">        I am child    </button></div><script>    var parent = document.getElementById('parnet');     parent.addEventListener('click', function() {        alert("Parent is clicked");     })    var child = document.getElementById('child');     child.addEventListener('click', function(){        alert("Child is clicked");     });</script>
Enter fullscreen mode Exit fullscreen mode

In this example, we have added an event listener to our parent and child. So when we click on "child" we should see an alert with "Child is clicked" only right? But we see two alert boxes first with a message "Child is clicked" and then with "Parent is clicked".

What happens behind the scenes is that when we trigger the click event on the child, the event propagates up to the parent triggering all the handler on its way. This is called "bubbling".

If we want to stop the propagation at some point, then we have a method called "event.stopPropagation()". This will stop the handler from being called on the particular div. But all other handlers will execute, if we want to stop all the handlers we use "event.stopImmediatePropagation()".

Thanks For Reading | Happy Coding

Get weekly newsletter of amazing articles i posted this week and some offers or announcement. Subscribe from Here


Original Link: https://dev.to/rahxuls/what-is-event-bubbling-in-javascript-82m

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To