0

How can you avoid a child element that is absolutely positioned to trigger the parent click handler?

If I click the div, it triggers clickMe().

<div onclick="clickMe()" style="height: 1600px; background: blue;">
    <div> Test </div>
</div>

   function clickMe() {
      console.log("CLICK ME CLICKED")
   }

Is the only way to prevent it by using a click handler on div to stop propgation?

  <div onclick="clickMe()" style="height: 1600px; background: blue;">
      <div onclick="buttonClicked()"> Test </div>
   </div>
   function clickMe() {
      console.log("CLICK ME CLICKED")
   }
   function buttonClicked() {
      event.stopPropagation();
   }
DaBosco
  • 43
  • 4
  • Alternate option is to check if `event.target` is same as `event.currentTarget` or not. If it is not, then return from the event handler function. This won't stop the parent click handler from triggering but it will prevent the event handler from executing completely. – Yousaf Dec 07 '20 at 18:16

1 Answers1

0

You are using inline event attributes (onclick) and the Global event object, which is a 20+ year old technique and should not be used today. Use .addEventListener() separate from your HTML and set your event handling functions to take event as an argument (because all DOM event handlers are automatically passed a reference to the event object that was created when the event was fired). Then, check event.target in the handler to make sure you only act when the correct element triggered the event.

In fact, in many situations, instead of setting up several event handlers on nested items and then dealing with propagation, as you are here, you can just let the bubbling happen with a single event handler set up on an ancestor element and decide how to proceed based on that event.target. This is called "event delegation".

You should also strive to avoid inline styles as well and instead use CSS classes to apply styling.

// Set your events up in JavaScript, not with 
// inline HTML event attributes
document.addEventListener("click", function(evt){
  // Check to see if the desired element was the
  // source of the event
  if(evt.target.classList.contains("clickMe")){
    // Perform the appropriate actions for this element
    console.log("CLICK ME CLICKED");  
  }
});
.clickMe {
  height: 1600px; 
  background: blue;
  color:yellow;
}
<div class="clickMe">
   <div> Test </div>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71