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

129
Views
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 answers
Answer question

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 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!