I've got the following markup on the page
<div id="box">
<div id="box_child_one"></div>
<div id="box_child_two"></div>
<div id="box_child_three"></div>
</div>
I need to trigger the onmousedown event on all elements inside the #box div so i've got this javascript code:
var element = "#box";
document.querySelector(element).onmousedown = function() {
alert("triggered");
};
However, I do not want onm ousedown being triggered on the #box_child_three element. How can I achieve this?
Thank you.
CodePudding user response:
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>
CodePudding user response:
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>
