Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

<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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!