I made a simple menu. When you click on the block element that says "Button", a submenu appears. You can remove submenus by clicking on an empty area of ​​the screen. And how to make sure that it was removed when you click on the block element again? enter image description here

    1 answer 1

    Use the toggle () method:

    Option 1 - if you need to hide / show the menu when you press the button

    $(".test").on("click", function() { $(".menu").toggle(); }); 
     .test { width:100px; background: #dfdfdf; padding:5px; cursor:pointer; } .menu { display: none; margin-top:10px; width: 150px; height: 150px; background: #d3d3d3; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test">кнопка</div> <div class="menu">меню</div> 

    Option 2 - if you want to hide / show the menu when you click on the button, as well as if you want to hide the menu when you click outside the menu

     $(document).on("click", function(e) { if (e.target.id != 'test' && e.target.id != 'menu') { $("#menu").hide(); } else if (e.target.id != 'menu') { $("#menu").toggle(); } }); 
     #test { width: 100px; background: #dfdfdf; padding: 5px; cursor: pointer; } #menu { display: none; margin-top: 10px; width: 150px; height: 150px; background: #d3d3d3; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test">кнопка</div> <div id="menu">меню</div> 

    • And how to make it so that when you click on an empty area, the submenu closes? - user226023
    • @ user226023 And what do you mean by an empty submenu area? - Alex
    • one
      @ user226023, stackoverflow.com/a/36549967/4928642 - Qwertiy