简体   繁体   中英

How to catch “closing” click event?

Here's an example. This is Google menu.

在此处输入图片说明

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?

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

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";
}

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