We are talking about how to stop an event bubbling and capturing in JavaScript. Let’s see…
When events in bubbling and capturing phases then how to stop an events from further propagation in capturing and bubbling phases, will discuss it now
So basically in this case, we call the
event.stopPropagation();
method in the event handler.
Note: event.stopPropagation()
method doesn’t stop any default behaviors of the element e.g., link click, checkbox checked. If you want to stop default behaviors, you can use the event.preventDefault()
method.
Suppose that you have a button inside a <div>
:
<div id="box-wrapper"> <button class="btn-info">Signup</button> </div>
When we click the button, the event is bubbling to the <div>
element. The following code shows two alert boxes when you click the button:
const btn = document.querySelector('.btn-info'); const box = document.querySelector('#box-wrapper'); btn.addEventListener('click', function (e) { alert('The Signup button was clicked!'); }); box.addEventListener('click', function (e) { alert('The box was clicked!'); })
To prevent the click event from propagating to <div>
element, you call the stopPropagation()
method in the event handler of the button:
btn.addEventListener('click', function (e) { alert('The button was clicked!'); e.stopPropagation(); });
Now, only one alert box displays when you click the button.
If this article is helpful, please comment below.