Skip to content Skip to sidebar Skip to footer

Preventing Event Bubbling

function clickHide(){ if (MouseEvent.button === 0) hide(); } function hide(){ using.style.display = 'none'; hidden.style.display = 'none'; } I have a problem with even

Solution 1:

You should use Event.stopPropagation(). Simply just call the stopPropagation() method on the event you are listening to.

Also see here for more info.

Edit: You can try it like this, it will only fire the event when you click on the parent element. The if statement checks if the target of the event is the parent element then calls hide() if not then it returns nothing.

const parentElement = document.querySelector(".parentElement");
const childElement = document.querySelector(".childElement");
parentElement.addEventListener("click", clickHide);

functionclickHide(event) {
  if(event.target !== parentElement){
      return;
  } 
  hide();
  
}
functionhide() {
    parentElement.classList.add('hidden');
}
<!DOCTYPE html><html><head><metacharset="utf-8" /><metahttp-equiv="X-UA-Compatible"content="IE=edge" /><title></title><metaname="description"content="" /><metaname="viewport"content="width=device-width, initial-scale=1" /><linkhref="" /><style>.parentElement {
        border: 20px solid red;
      }

      .childElement {
        background: yellow;
        padding: 20px;
      }

      .hidden {
        display: none;
      }
    </style><scriptsrc="test.js"asyncdefer></script></head><body><divclass="parentElement"><divclass="childElement"></div></div></body></html>

Post a Comment for "Preventing Event Bubbling"