Skip to content Skip to sidebar Skip to footer

Close The Menu On Click

I want to close my menu by clicking on a link or when I click outside the menu. In the interest of keeping things nice and light, I don't want to use jQuery. How do I do it?

Solution 1:

It can be done with DOM API using addEventListener() on document. You then need logic to find if the click target was on the menu or any of its elements, or somewhere else on the page.

isDescendent() borrowed from How to check in Javascript if one element is contained within another

The menu can then be hidden with element.style.display = 'none'

I would question motivation to not use jQuery, you'll be making a lot more work for yourself in the long run...

var menu = document.querySelector("nav.nav");
var checkbox = document.querySelector("input[type=checkbox]");

document.addEventListener("click", function(e) {
  if (menu != e.target && 
      ! isDescendant(menu, e.target)) {
    console.log("Clicked somewhere else");
    menu.style.display = 'none';
    checkbox.checked = false;
  }
  
}, false);

functionisDescendant(parent, child) {
     var node = child.parentNode;
     while (node != null) {
         if (node == parent) {
             returntrue;
         }
         node = node.parentNode;
     }
     returnfalse;
}
<div>
  Rest of page...
</div><navclass="nav"><divclass="nav__left"><h3><ahref="#home">DenisMasot</a></h3></div><inputtype="checkbox" /><labelclass="burger"for="nav"></label><ulclass="nav__right"><liclass="active"><h3><ahref="#home">home</a></h3></li><li><h3><ahref="#about">À propos</a></h3></li><li><h3><ahref="#production">Réalisation</a></h3></li><li><h3><ahref="#contact">Contact</a></h3></li></ul></nav>

Solution 2:

one way, hope it helps

    $(document).ready(function() {
        $('.click').click(function() {
                $('.nav__right').slideToggle("fast");
        });
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script><navclass="nav"><divclass="nav__left"><h3><ahref="#home">DenisMasot</a></h3></div><inputtype="checkbox" /><labelclass="burger"for="nav"></label><buttonclass="click">click me</button><ulclass="nav__right"><liclass="active"><h3><ahref="#home">home</a></h3></li><li><h3><ahref="#about">À propos</a></h3></li><li><h3><ahref="#production">Réalisation</a></h3></li><li><h3><ahref="#contact">Contact</a></h3></li></ul></nav>

Post a Comment for "Close The Menu On Click"