I've built some navigation (for mobile web) that uses the toggleClass method in jQuery to hide and reveal the menu. Clicking on the 'MENU' icon/button toggles the class '.active' (display: hidden) on and off of the menu div.
I've been desperately searching for a way to hide the menu by clicking outside of it (anywhere on the page). Currently, the only way to close the menu is to click on the MENU button again, which toggles the div back to the .active class (hidden).
I haven't been able to find any examples similar to this with a solution on how that is done.
$(document).ready(function() {
$(".toggle-nav").click(function(e) {
$(this).toggleClass("active");
$(".menu ul").toggleClass("active");
e.preventDefault();
});
});
/* .toggle-nav is the menu icon/button. */
.toggle-nav {
font-size: 20px;
margin-left: 7px;
}
/* The .active class hides the menu by default.
When .toggle-nav (menu icon) is clicked, .active class is 'turned off',
revealing the menu. When clicked again, it hides the menu. */
.menu ul.active {
display: none;
}
.menu ul {
width: 10em;
position: absolute;
top: 60%;
padding: 10px 18px;
background: #e6e5e4;
}
.menu li {
margin: 5px 0px 5px 0px;
float: none;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="menu">
<a class="toggle-nav" href="#">MENU</a>
<ul class="active">
<li><a href="#">Item One</a></li>
<li><a href="#">Item Two</a></li>
<li><a href="#">Item Three</a></li>
</ul>
</div>