Close a sidebar when I click outside of it

  css, html, javascript, menu

I am trying to close a sidebar when I click outside of it.
I have added a condition to only close it if it is open (nav_active), but I am missing something.
The expected behavior would be to display the alert when I click inside or outside the red box.

"use strict";

var burger = document.querySelector('.burger');
var nav = document.querySelector('.nav_links');

var navSlide = function navSlide() {
  burger.addEventListener('click', function () {
    nav.classList.toggle('nav_active');
  });
  
  if (nav.classList.contains("nav_active")) {
    window.addEventListener('click', function(e) {
      if (nav.contains(e.target)) {
        alert("Clicked in Box");
      }
      else {
        alert("Clicked outside Box");
      }
    });
  }
};

navSlide();
.nav_home, .nav_links, .nav_buttons, .nav_list {
  display: inline-block;
  vertical-align: middle;
}

.burger {
  width: 2.4rem;
  height: 2.4rem;
  margin: auto 0;
  cursor: pointer;
  background: black;
}


.nav_list a:hover {
  text-decoration: line-through !important;
}


  .nav_links {
    display: block;
    z-index: 0;
    position: absolute;
    right: 0rem;
    width: 80%;
    margin-right: 0.1rem;
    border-left: 0.1rem solid;
    background: red;
  }

  .nav_item {
    display: block;
  }

  .nav_list {
    display: block;
    a {
      display: block;
    }
    span {
      display: none;
    }
  }
  
  .nav_active {
  display: inline-block;
}
<header id="header">

  <div class="header container">


    <div class="nav_links">

      <h5 class="nav_list">
        <span class="noselect">⁄</span>
      </h5>

      <div class="nav_buttons">

        <h5 class="theme-label"></h5>

        <input class="themeSwitch" type="checkbox" id="switch" name="theme"/>

        <label class="toggle" for="switch"></label>

        <label class="switch" for="switch"></label>

      </div>

    </div>

    <div class="burger"></div>

  </div>

</header>

Source: Ask Javascript Questions

LEAVE A COMMENT