I want to make a menu that opens when you click a button and closes when you click on any part of the screen. The problem is that the menu closes when you click anywhere, except for the open button. According to my idea, after opening the menu, the class at the button is removed and it should become inactive, which means it becomes the same as any part of the document, but for some reason this does not happen. What's my mistake?

$(document).ready(function() { $(hidden).slideUp(); $('.switch').click(function() { $(hidden).slideDown(300); $('#drop-but').removeClass('switch'); return false; }); $(document).click(function() { $(hidden).slideUp(300); $('#drop-but').addClass('switch'); }); }); 
  • Put the entire current code together with html markup. I will help - Urmuz Tagizade

2 answers 2

As an option:

 $(function() { $('.menu-wrap').on('click', function() { var $this = $(this); if ($this.hasClass('active')) { $this.removeClass('active'); $(document).off('click.menu'); } else { $this.addClass('active'); $(document).on('click.menu', function(e) { if ($(e.target).closest('.menu-wrap').length === 0) { $('.menu-wrap').removeClass('active'); $(document).off('click.menu'); } }); } }); }); 
 .menu-wrap { position: relative; width: 100px; } .menu-title { width: 100%; border: 1px solid black; cursor: pointer; transition: all .5s; } .menu-wrap.active .menu { visibility: visible; opacity: 1; } .menu { border: 1px solid black; border-top: none; width: 100%; visibility: hidden; opacity: 0; transition: all .5s; } ul { list-style-type: none; margin: 0; padding: 0; } li:hover { cursor: pointer; background: #eee; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="menu-wrap"> <div class="menu-title"> menu toogle </div> <div class="menu"> <ul> <li>item1</li> <li>item2</li> <li>item3</li> </ul> </div> </div> 

    The fact is that this handler:

     $('.switch').click(function() { $(hidden).slideDown(300); $('#drop-but').removeClass('switch'); return false; }); 

    Cancels all handlers on .switch that come after it. Not to cancel instead

     return false; 

    make

     e.preventDefault(); 

    Accordingly, e must be specified as an input parameter.

     $('.switch').click(function(e) {