Skip to content Skip to sidebar Skip to footer

How To Close Site Navbar When Onclick Outside?

I created site navbar but don't know how to close this when user click outside. I tried 'focus' on hamburger button, but it's not great way. Actually I used 'toggleClass' in javasc

Solution 1:

  1. One solution would be adding an overlay under your menu and close menu on click event of this overlay.
  2. Another one is checking in click event of whole document if menu is opened and something outside of it was clicked.
  3. Using focusout or blur event is yet another solution, but it needs to be remembered that it requires tabindex attribute for such HTML elements as div or ul.

Below you may find working example of the second approach.

hamburger = document.getElementById('hamburger');
menu = document.getElementById('menu');
hamburger.addEventListener('click',function(event){
       menu.classList.toggle('open');
      });
      
document.addEventListener('click', function(event) {
  if(menu.classList.contains('open') && !event.target.isEqualNode(hamburger) && !event.target.isEqualNode(menu) && !menu.contains(event.target)) {
      menu.classList.remove('open');
  }
});
.menu {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        position: fixed;
        width: 40%;
        height: 100%;
        background-color: rgba(26, 23, 36, 0.96);
        border-right: 1px solid #8383a2;
        transform: translateX(-100%);
        transition: 0.3s transform linear;
        padding-left: 0;
    }
        .open {
        transform: translateX(0%);
    }
<buttonid="hamburger">
            I am hamburger
        </button><ulclass="menu"id = "menu" ><li><ahref="#" >Main </a></li><li><ahref="#"> Blog </a></li><li><ahref="#"> Contact </a></li><li><ahref="#"> More </a></li></ul>

Solution 2:

Try using the focusout or blur event handlers on your menu element.

For example:

menu.addEventListener('focusout', (event) => {
    // close the menu  
});

Following @matvs's comment: you might also need to add the tabindex attribute to your menu element, in order for its focusout/blur event to be triggered. For example:

<ul class="menu" tabindex="0">

Solution 3:

you can use a click listener, for example, I have 2 sections <section id="content">...</section> and <section id="navbar">...</section>, you can use a listener inside the section with id content e.g:

$('section#content').click(function(){
    $('section#navbar').css("display", "none") //or use a spacific class
}) 

Solution 4:

You can also use try node.contains()(doc) function inside click handler to check whether an event target is a descendant of a given node.

Like

if (!menu.contains(event.target)) {
  // close the menu
}

Post a Comment for "How To Close Site Navbar When Onclick Outside?"