Skip to content
Advertisement

How to block click event on child element using parent element

    <div id="parent">
      <div>
         <button onClick={() => console.log("a")}>a</button>
      </div>
      <button onClick={() => console.log("b")}>b</button>
      <button onClick={() => console.log("c")}>c</button>
    </div>

As above, it has a parent element and a child element. In this situation, is it possible to prevent the child element from being clicked through the parent element, or to prevent the child element’s onclick event from being fired?

In the above situation, console.log should not be generated no matter which button is clicked.

There is a way to cover the parent element by adding another element, but I’m curious how to prevent it through only the parent element.

Advertisement

Answer

For vanilla JavaScript, there’s also a way to prevent the child events from triggering even they’re assigned beforehand.

You may add a click event to the parent, set useCapture by assigning the third parameter to true in the addEventListener function and then e.stopPropagation in the function body.

This will make sure this event triggers before normal event phases, so all its child click events will not trigger. It also keeps the buttons clickable and will not alter their appearance.

document.querySelector('#parent').addEventListener('click', e => e.stopPropagation(), true);
<div id="parent">
  <div>
     <button onclick="console.log('a')">a</button>
  </div>
  <button onclick="console.log('b')">b</button>
  <button onclick="console.log('c')">c</button>
</div>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement