Sam
Sam

Reputation: 61

Javascript menu close

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

Upvotes: 0

Views: 82

Answers (3)

JackHasaKeyboard
JackHasaKeyboard

Reputation: 1665

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

Upvotes: 0

DJAy
DJAy

Reputation: 330

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/

Upvotes: 1

Mike Dirlek
Mike Dirlek

Reputation: 1

Creating an onclick listener for document should be sufficient:

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

Upvotes: 0

Related Questions