1

In current Github website, there is a toggle ability to show/hide the profile menu. on the following screen-shot, there is a transparent layer with full width and height behind the menu and if for example I click on "Explore", my first click will trigger the onclick event on the transparent layer and it only will hide the menu and transparent layer itself. Then I need to click again on "Explore" to make action.

enter image description here

but in current stackoverflow website, there is similar toggle ability without above limitation and when the menu is open, I can act like a normal webpage without any limitation to Select, Hover and click.

enter image description here

In both of websites when you click around, the menu will close, but I could not find any transparent layer in stackoverflow and I am not sure these are using the similar way.

As I know there is several ways to solve these problems:

Simulate a click by using x,y

It is not the correct answer, because in this way, it is not possible to use hover like what stackoverflow is doing now (you can hover over any objects behind the menu).

Make an element “invisible” to clicks

It is not the correct answer, because in this way, it is not possible to use onclick event to hide menu itself.

JavaScript to prevent Default action

It is not the correct answer, because in this way, it is not possible to use hover and onclick events at the same time. then it is not possible to make it like stackoverflow.

Can you please guide me how stackoverflow is passing the Github limitation?

Reza Amya
  • 1,494
  • 2
  • 25
  • 40

2 Answers2

1

Just don't create a transparent overlay at all.

Instead listen for the click event on document and close the menu if it's fired.

document.querySelector('button').addEventListener('click', e => {
  console.log('button clicked')
})

document.addEventListener('click', e => {
  console.log('click reached document, close menu')
})
<div>
 <button>Click me</button>
</div>
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
0

First you need to toggle menu using classes like this:

when it is close:

<div class="menu">...</div>

when it is open:

<div class="menu open">...</div>

and in CSS:

.menu {
    display: none;
}

.menu.open {
    display: block;
}

then you need to add an onclick event on the document to find all open menus and remove open class of them.

<script type="text/javascript" language="JavaScript">
    document.onclick = closeAllOpenMenus;

    function closeAllOpenMenus() {
        const all_open_menus = document.querySelectorAll(".menu.open");

        [].forEach.call(all_open_menus, function(el) {
            //remove 'open' class
            el.classList.remove("open");
        });
    }
</script>

you need to work more on the above function to prevent closeAllOpenMenus when the user is clicked over the menu itself.

Reza Amya
  • 1,494
  • 2
  • 25
  • 40