To stop an event from further propagation in the capturing and bubbling phases, you call the Event.stopPropation()
method in the event handler.
Event.stopPropagation();
Code language: CSS (css)
Note that the 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">
<button class="btn">Register</button>
</div>
Code language: HTML, XML (xml)
When you 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');
const box = document.querySelector('#box');
btn.addEventListener('click', function (e) {
alert('The button was clicked!');
});
box.addEventListener('click', function (e) {
alert('The box was clicked!');
});
Code language: JavaScript (javascript)
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();
});
Code language: JavaScript (javascript)
Now, only one alert box displays when you click the button.