How to prevent child element executing onmousedown event
Solution 1:
Check event.target
to find out which element was actually clicked on.
var element = "#box";
document.querySelector(element).onmousedown = function(e) {
if (e.target.id !== "box_child_three") {
alert("triggered");
}
};
<div id="box">
<div id="box_child_one">one</div>
<div id="box_child_two">two</div>
<div id="box_child_three">three</div>
</div>
Solution 2:
You need to stopPropagation
for the event when element three is clicked so that it doesn't bubble up to the parent (box
) element.
document.getElementById('box').addEventListener('click', () =>
alert('triggered')
);
document.getElementById('box_child_three').addEventListener('click', e =>
e.stopPropagation()
);
<div id="box">
<div id="box_child_one">one</div>
<div id="box_child_two">two</div>
<div id="box_child_three">three</div>
</div>