LandonRaymond
LandonRaymond

Reputation: 73

How to prevent child element executing onmousedown event

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 onmousedown being triggered on the #box_child_three element. How can I achieve this?

Thank you.

Upvotes: 0

Views: 741

Answers (3)

anotherRandomGuy
anotherRandomGuy

Reputation: 11

<div id="box">
    <div id="box_child_one" trigger></div>
    <div id="box_child_two" trigger></div>
    <div id="box_child_three"></div>
</div>

<script>
document.querySelector('#box').onclick = function(e){
  if(e.target.hasAttribute('trigger')){
    alert('event fired')
  }
}
</script>

I'd go for this. As you are now no longer relying on an id to carry this out making it more re-usable

Upvotes: 0

Tom
Tom

Reputation: 7740

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>

Upvotes: 1

Barmar
Barmar

Reputation: 780655

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>

Upvotes: 1

Related Questions