0

I want to use pure javascript (not jquery) to close a pure css drop-down menu I have created when clicking outside of the menu. How can I do this?

HTML:

<ul>
    <div class="submenu">
        <ul></ul>
    </div>
    <div class="submenu">
        <ul></ul>
    </div>
</ul>

That's the basic structure of my HTML. I want to close the submenu if clicking outside of the submenu. Any way to do so with pure javascript? So far I've tried this:

Javascript:

        <script>
            document.onclick = closeMenu();
            function closeMenu() {
                document.getElementsByClassName("submenu").style.display = 'none';
            }
        </script>

This doesn't seem to work. Any ideas?

1 Answers1

0

A few changes: you are assigning the onclick incorrectly, it should be a reference to your function, not the result of calling your function:

 document.onclick = closeMenu;

Second, you need to use event delegation to determine if the clicked element is a descendent of your submenu div. Something like this function should work for figuring out if the event target node is a child of submenu:

function parentIsSubmenu(child) {
     var node = child.parentNode;
     while (node != null) {
         if ((node.className || '').indexOf('submenu') > -1) {
             return true;
         }
         node = node.parentNode;
     }
     return false;
}

Alter your closeMenu function to check if the clicked element is a child of submenu, if not, loop through each submenu item and set display to none (what you currently have would not work).

function closeMenu(event) {
    if(!parentIsSubmenu(event.target)) {
        var submenus = document.getElementsByClassName("submenu");
        for(var i = 0; i < submenus.length; i++) {
            submenus[i].style.display = 'none';
        }
    }
}

Here is a working example: https://jsfiddle.net/m2muz5en/

Rob M.
  • 35,491
  • 6
  • 51
  • 50