Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda