Prevent click on outer element while clicking on inner element – Javascript
How can I prevent clicking on the outer element while clicking on the inner element with js events?
It is quite simple, let’s see the below example code.
<div id=”parent_element” onclick="alert('outer element')">Outer element <div id=”child_element” onclick="alert('inner element'); event.stopPropagation(); ">Inner element</div> </div>
So, when we click on the inner element, it will actually trigger the two events one is the inner element and another will be of the parent element.
This is also called event bubbling in javascript. Where Bubbling means the most of the javascript events trigger from target element to its parent elements.
Event bubbling start from bottom to up elements.
Javascript example to use event stopPropagation
Javascript code is as given below.
document.querySelector("#parent_element").addEventListener('click', function() { alert('outer element'); }) document.querySelector("#child_element").addEventListener('click', function(e) { e.stopPropagation(); alert('inner element'); })
In the jQuery use of event stop propagation
In jQuery the solution will be like below.
$(“#parent_element”).on(‘click’, function() { alert(‘outer element’); }) $(“#child_element”).on(‘click’, function(e) { e.stopPropagation(); alert(inner element’); })
Hence, we can use stop propagation on the inner element to prevent its click bubbling to the outer element.