Question

Here’s an example. This is Google menu.

enter image description here

When you click on the gear-wheel (red cross) the menu appears. When you click anywhere beyond opened menu (green cross) the menu disappear. The question is how to catch that second closing event (green cross).

It’s simple to open the menu.

var x = document.getElementById("star");          // this is id of the gear-wheel;
var y = document.getElementById("hiddenMenu");    // this is id of the menu with display = none;
x.onclick = function() {
    y.style.display = "block";
}

But how to make it closed? I tried this way using "body" tag:

var bar = document.getElementsByTagName("body")[0];
bar.onclick = function() {
    if (y.style.display == "block") {
       y.style.display = "none";
    }
}

But the menu is closed immediately after it has been opened. First it becomes “block” as “star” is clicked. But immediately after this becomes “none” as body is also clicked. How to solve it? Is it really necessary to write code for "body" for catching right target event?

Was it helpful?

Solution

star.addEventListener("click", closeIfOpen);
document.addEventListener("click", closeIfClickOutsideMenu);

OTHER TIPS

This is due to bubbling/event propagation. The listener on #star fires first, then the event bubbles up to the body and it fires there.

You need to cancel event propagation. Unfortunately this is not particularly easy using inline handlers without a library.

var x = document.getElementById("star");          // this is id of the gear-wheel;
var y = document.getElementById("hiddenMenu");    // this is id of the menu with display = none;
x.onclick = function(e) {
    e = e || window.event;
    if (e.stopPropagation) {
        e.stopPropagation();
    }else{
        e.cancelBubble = true;
    }

    y.style.display = "block";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top