简体   繁体   中英

stop passing function from parent to child elements javascript

I want parent element to disappear when clicking on it

But I want also all child elements to stop implement this function as when clicking on it the parent element hide

I want a solution in Vanilla javascript


var listmenu = document.querySelector(".list-overlay");// this list menu nested in overlay element but when click on it also parent element hide but i want no action when click on it  

overlay.addEventListener("click",hide);


  function hide(){
      overlay.classList.add("hide");

  }

You should use stopPropagation to stop the event from the child elements bubbling to the parent element.

I added an example here.

 function hideParent() { document.getElementById('parent').style.display = 'none'; } function onChildClick1(event) { event.stopPropagation(); } document.getElementById('child1').addEventListener('click', onChildClick1);
 #parent { height: 80px; background: red; } #child1 { height: 30px; background: blue; color: white; } #child2 { height: 30px; background: green; color: white; }
 <div id="parent" onclick="hideParent()"> THIS IS THE PARENT <div id="child1"> CHILD: STOP PROPAGATION <!-- will *not* trigger parent and remain visible --> </div> <div id="child2"> CHILD: DEFAULT BEHAVIOR <!-- will trigger parent and hide --> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM