jquery close on click outside

13,614
$('body').on('click',function(event){
   if(!$(event.target).is('#nav-toggle')){
     $("#page").removeClass("margin");
   }
});
Share:
13,614
sam
Author by

sam

Updated on August 26, 2022

Comments

  • sam
    sam almost 2 years

    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.