0

I have a menu in HTML. When you click "menu", a list opens, click "menu" again, the list closes.

I need the menu to close if the user clicks anywhere on the screen

<script type="text/javascript">
$(function() {
  var menuVisible = false;

    $('#menuBtn').click(function() { 
    if (menuVisible) {
      $('#menu').css({
        'display': 'none'
      });
      menuVisible = false;
      return;
    }
    $('#menu').css({
      'display': 'block'
    });
    menuVisible = true;
  });
  $('#menu').click(function() {
    $(this).css({
      'display': 'none'
    });
    menuVisible = false;
  });
});

Krish Munot
  • 1,093
  • 2
  • 18
  • 29
Sam
  • 51
  • 5
  • Possible duplicate of [jQuery: Close DIV by clicking anywhere apart from the DIV itself?](http://stackoverflow.com/questions/6610022/jquery-close-div-by-clicking-anywhere-apart-from-the-div-itself) – Patrick Evans Jun 12 '16 at 23:23

3 Answers3

1

Here is simple Html and jquery. Hope it will help you.

Html -

<div class="container">
  <button id="menu">menu</button>
  <div id="list">list</div>
</div>

jQuery -

$('#menu').click(function(e) {
    e.stopPropagation();
    $('#list').slideToggle();
})
$('#list').click(function(e) {
    e.stopPropagation();
});
$('body').click(function() {
    $('#list').slideUp();
})

List will toggle on click of menu and slideUp on body click.

jsFiddle - https://jsfiddle.net/dhananjaymane11/Lgfdmjgb/1/

DJAy
  • 330
  • 1
  • 9
0

Creating an onclick listener for document should be sufficient:

document.onclick = myClickAnywhereHandler;
function myClickAnywhereHandler() {
  alert("hide the menu");
  $('#menu').css({
    'display': 'none'
  });
}
0

jQuery's .toggle function toggles an elements visibility, that code with the boolean value logic isn't necessary.

Just call .toggle on the menu whenever there's a click within the document.

$(document).click(function(){
  $("#menu").toggle();
});
JackHasaKeyboard
  • 1,599
  • 1
  • 16
  • 29