Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

<nav class="nav">
  <div class="nav__left">
    <h3><a href="#home">DenisMasot</a></h3>
  </div>
  <input type="checkbox" /><label class="burger" for="nav"></label>
  <ul  class="nav__right">
    <li class="active">
      <h3><a href="#home">home</a></h3>
    </li>
    <li>
      <h3><a href="#about">À propos</a></h3>
    </li>
    <li>
      <h3><a href="#production">Réalisation</a></h3>
    </li>
    <li>
      <h3><a href="#contact">Contact</a></h3>
    </li>
  </ul>
</nav>
like image 457
DenisMasot Avatar asked Mar 05 '26 07:03

DenisMasot


1 Answers

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);

function isDescendant(parent, child) {
     var node = child.parentNode;
     while (node != null) {
         if (node == parent) {
             return true;
         }
         node = node.parentNode;
     }
     return false;
}
<div>
  Rest of page...
</div>

<nav class="nav">
    <div class="nav__left">
      <h3><a href="#home">DenisMasot</a></h3>
    </div>
    <input type="checkbox" /><label class="burger" for="nav"></label>
    <ul  class="nav__right">
      <li class="active">
        <h3><a href="#home">home</a></h3>
      </li>
      <li>
        <h3><a href="#about">À propos</a></h3>
      </li>
      <li>
        <h3><a href="#production">Réalisation</a></h3>
      </li>
      <li>
        <h3><a href="#contact">Contact</a></h3>
      </li>
    </ul>
  </nav>
like image 120
Adam Avatar answered Mar 06 '26 20:03

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!