Reputation: 57
i have made a side navigation menu which slides from left to right on the click of a button.
$(document).ready(function(){
$("#nav-toggle").click(function(){
$("#page").toggleClass("margin");
});
});
when the '#nav-toggle' button is clicked the '#page' margin increases from 0px to 600px.
.margin {
margin-left:600px;width:380px;overflow-x:hidden
}
<div id="side-menu">
<nav>
<a class="nav-links" href="#home">home</a>
<a class="nav-links" href="#about">about</a>
<a class="nav-links" href="#contact">contact</a>
</nav><!-- end of nav -->
how would i close the menu by clicking outside of it.
Upvotes: 4
Views: 17388
Reputation: 316
Easy ... use delegates explained here: http://api.jquery.com/on/ "Check Direct and delegated events"
basically what i say is ... when the user clicks anywhere on the document and the source is not inside the #side-menu :not(#side-menu) remove the class margin from the #nav-toggle
$(document).on({
click: function(){
$("#nav-toggle").removeClass("margin")
}
},":not(#side-menu)");
Upvotes: 0
Reputation: 44740
$('body').on('click',function(event){
if(!$(event.target).is('#nav-toggle')){
$("#page").removeClass("margin");
}
});
Upvotes: 14