Don't trigger main container click if clicking in specific child element

542 views Asked by At

I have a click listener attached to my #main container

main.addEventListener("click", function() {
    console.log("clicked main");
});

Within my main container I have an #element also with a click listener

element.addEventListener("click", function() {
    console.log("clicked element but dont trigger main click");
});

How do I avoid triggering the #main click when clicking within #element ?

Fiddle: http://jsfiddle.net/gufo7mmc/1/

1

There are 1 answers

6
AmmarCSE On

Use event.stopPropagation()

element.addEventListener("click", function() {
    console.log("clicked element but dont trigger main click");
    event.stopPropagation();
});

var main = document.getElementById("main");
var element = document.getElementById("element");
var textElement = document.getElementById("text");

main.addEventListener("click", function() {
    console.log("clicked main");
});

main.addEventListener("mouseenter", function() {
    textElement.style.visibility = "visible";
    console.log("trigger on everything except #element");
});

main.addEventListener("mouseleave", function() {
    textElement.style.visibility = "hidden";
});

element.addEventListener("click", function() {
    console.log("clicked element but dont trigger main click");
    event.stopPropagation();
});
#main {
    position: absolute;
    width: 300px;
    height: 600px;
    
    background-color: red;
}

#element {
    position: absolute;
    width: 100%;
    height: 100px;
    
    background-color: green;
}

#text {
    position: absolute;
    width: 100px;
    height: 100px;
    top: 200px;
    
    background-color: blue;
    visibility: hidden;
}
<div id="main">
    <div id="element"></div>
    <div id="text">HELLO</div>
</div>