Home > Blockchain >  Prevent onClick of base element if onClick of overlay button is clicked
Prevent onClick of base element if onClick of overlay button is clicked

Time:03-09

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

CodePudding user response:

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" >
  <button  id="xAndDiv" >X & Div </button>
  <button  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

  • Related