We can use event.stopPropagation() for stopping event bubbling. Can we use same method for stopping event capturing also?
If no how can we achieve it?
If a listener has been added to the capturing phase, rather than the bubbling phase, then you can prevent the event from capturing down to child elements with the same method: event.stopPropagation()
.
For example, in this code, you'll see that #inner
's listener is never triggered, because #outer
's listener stops the event from propagating downward:
document.querySelector('#outer').addEventListener(
'click',
function(event) {
console.log('propagation stopped');
event.stopPropagation();
},
true // Add listener to *capturing* phase
);
document.querySelector('#inner').addEventListener(
'click',
function(e) {
console.log('inner clicked');
}
);
<div id="outer">
outer
<div id="inner">
inner
</div>
</div>