0

I currently have a menu that appears when a mobile button is clicked. When a user clicks off the div, I want the div to hide. Right now, I have an 'X' the user must click to hide the div. How can I accomplish what I'm trying to do? (I believe I included all necessary code - but if I missed something, let me know.)

Thank you in advance!

HTML

<div class="nav-mobile">
    <a href="#link1">Menu Item 1</a>
    <a href="#link2">Menu Item 2</a>
</div>

JS

if (nav-mobile) {
  nav-mobile.addEventListener('click', () => {
    nav.classList.toggle('active');
  });
}

SCSS

(by default is hidden)

.nav-mobile {
  visibility: hidden;
}

(when mobile navigation is active, it becomes visible)

&.active {
  .nav-mobile {
    visibility: visible;
    opacity: 1;
    h5:not(nav-mobile-title) {
      margin: 0;
    }
  }
}
  • 1
    In theory, I usually accomplish this by creating a `div` behind the menu that spans the width and height of the screen. This div should be absolutely positioned if there is no scroll height in the body, or fixed if you want to allow scrolling. When this div is click (which is anywhere except the menu) you can call a script to remove the menu. – Spencer May Sep 10 '18 at 17:41
  • @SpencerMay Thank you! That makes a lot of sense. I will try that. – entry-coder Sep 10 '18 at 17:42
  • Possible duplicate of [Use jQuery to hide a DIV when the user clicks outside of it](https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it) – showdev Sep 10 '18 at 17:46
  • Is it possible to see more of the HTML and JavaScript related to the nav-mobile ? – sphinxplayer Sep 10 '18 at 17:58
  • I would have previously agreed with @SpencerMay but in my experience this can sometimes cause problems when trying to scroll on a mobile device, where sometimes the user will be touching outside of the menu to scroll down, thus closing the menu. My 2cents would be to accomplish it with JavaScript, an example of which can be found with the recommendation from showdev. – lewisnewson Sep 11 '18 at 03:00

0 Answers0