Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
Prevent onClick of base element if onClick of overlay button is clicked

I have a <button> component overlayed on a <div> component that is shows an image.

The button component is a red [X] as shown in the picture below. I have a seperate onClick Listener for the <button> and the <div>. I want to make sure when the onClick of the button is fired, i.e. the [X] is clicked the onClick of the <div> should not run.

How to do this?

I have tried this, but it does not work
First the onClick of the <button> runs and then the onCLick of <div> runs

  const onClickButtonHandler = (event) => {
    event.preventDefault();
    console.log("BTN HANDLER")
  };

  const onClickDivHandler = (event) => {
    console.log("DIV HANDLER")
  };

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

document.getElementById('mydiv')
        .addEventListener('click', function (event) {
            console.log("div clicked")
        });
        
document.getElementById('xAndDiv')
        .addEventListener('click', function (event) {
            console.log("x clicked, div click also executes")
        });

document.getElementById('x')
        .addEventListener('click', function (event) {
            event.stopPropagation()
            console.log("only x click executes")
        });
.div {
    background-image: url( https://png.pngtree.com/thumb_back/fw800/back_our/20190628/ourmid/pngtree-clear-sample-newspaper-spring-forest-playground-background-design-image_276784.jpg);
    background-size: cover;
    height: 250px;
 }
 
 .x {
  color:red;
 }
<div id="mydiv" class="div">
  <button class="x" id="xAndDiv" >X & Div </button>
  <button class="x" id="x" >Only X</button>
</div>

You need to stop the propagation of event in the onclick of button

const onClickButtonHandler = (event) => {
    event.stopPropagation();
    console.log("BTN HANDLER")
  };

It prevents the event to bubble up to the parent level

codesandbox for react reference https://codesandbox.io/s/awesome-thunder-1x0coz?file=/src/App.js

Read more about stopPropagation at MDN

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda