I wrote a script that opens the drop-down menu and closes it when you click in any part of the window or when you click on the button that opens it. But the problem is that the drop-down menu is closed by clicking on it, which should not be. How to fix this?

$(function() { $('.dropdown').click(function() { $(this).nextAll('.dropdown-box').toggleClass('active'); }); $(window).click(function CloseDropDown(event) { var target = $(event.target); var dropdowns = $('.dropdown-box'); if(!target.is('.dropdown')) { dropdowns.each(function() { if($(this).hasClass('active')) { $(this).removeClass('active'); } }); } }); }); 

    2 answers 2

    You need to create a new div, and place it on top of the page, and the window on top of the diva:

     div.overlay{ background: rgba(0,0,0,0.5); position:fixed; top:0; left:0; right:0; bottom:0; z-index:1000; } .dropdown-box{ z-index:1001; } 

    And, accordingly, hang your script not on the window, but on click on this div, adding to this script the code for deleting the created div.

       $('.dropdown-box').click(function(event) { event.stopPropagation(); });