0

I'm calling a function by ONCLICK event for the div conatiner but it also being called when I click on its inner elements so how can I call the function only for the div container not for its inner elements?

I have added just Onclick event on the container div and calling my close function

function closeMenu() {
    var target = document.getElementById("login-container");
    target.style.opacity = "0";
    target.style.zIndex = "-10";
}
var closeBtn = document.getElementById("close-overlay");
closeBtn.addEventListener("click", closeMenu);

I dont wanna call the function if i click on its inner HTML elements, just for the container div.

  • You can find the answer here => [How do I prevent a parent's onclick event from firing when a child anchor is clicked?](https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli) – fullstack.studio Oct 21 '19 at 17:17
  • Possible duplicate of [How do I prevent a parent's onclick event from firing when a child anchor is clicked?](https://stackoverflow.com/questions/1369035/how-do-i-prevent-a-parents-onclick-event-from-firing-when-a-child-anchor-is-cli) –  Oct 21 '19 at 17:21

3 Answers3

1

I hope this helps.

function closeMenu(e) {
 if (e.target.id === "close-overlay"){
    var target = document.getElementById("login-container");
    target.style.opacity = "0";
    target.style.zIndex = "-10";
  }
}
var closeBtn = document.getElementById("close-overlay");
closeBtn.addEventListener("click", closeMenu);
Okkano
  • 230
  • 2
  • 9
0

You are looking to stop the propagation of the event. You just need to add e.stopPropagation();

Here is the code example of the same

Thanks

Vishal Biswas
  • 401
  • 2
  • 8
Neha Sharma
  • 732
  • 1
  • 4
  • 13
0
var closeBtn = document.getElementById("close-overlay");
closeBtn.addEventListener("click", closeMenu);

function closeMenu(e) {

 var child = document.getElementById("login-container"),
     parent = document.getElementById("close-overlay");

 if(e.target == parent){
    child.style.opacity = "0";
    child.style.zIndex = "-10";
  }

}

working example here

SamsonTheBrave
  • 527
  • 4
  • 10