Reputation: 61
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
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
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
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