I make drop-down menus, I want that when you click to any place outside the menu, it disappears. Is there some smart solution? Or do you have to make two containers with menus and with everything else and hang an onclick event on it to close the menu? It should be as dynamic as possible to make several menus.

    3 answers 3

    If I understand the question correctly, then about

    $('.menu').click(function () { // Показываем выпадающее меню $('body').click(function () { // Прячем выпадающее меню }); }); 

    Option .

    Markup

     <a class="menu" href="#">Меню</a> <div class="dropdown" style="display: none;"> <div><a href="#">Выбор 1</a></div> <div><a href="#">Выбор 2</a></div> </div> 

    Code

     $('.menu').click(function () { $('.dropdown').hide(); $(this).next().show(); return false; }); $('body, .dropdown a').click(function () { $('.dropdown').hide(); }); $('.dropdown a').click(function () { // TODO: Что-то сделать }); 
    • The same method also does not work correctly. It seems to be all right, but he also considers the button to open the menu for the body and immediately closes it, but it is necessary that when you click on the drop-down menu nothing happens. - Elected
    • Updated the answer. - stanislav

    Is there some smart solution?

    Yes, write OnClick () and hide the block that is not needed

    • More precisely, such a solution would be offered. But it does not work or is not correct. Yes, and you need to easily add new menus. - Elected
    • I tried it like this, but for some reason it doesn't work: $ ('# wrap'). Click (function () {$ ('# MyProfile'). Hide ();}); Before you hide a block, you need to show it. Such functions do not work, because it cannot show the block, it hides it immediately, that it does not even have time to open. - Elected
    • one
      "such a solution was suggested" - but to sit down, think and write no longer? Or is it now a new fashion on "mouse programmers"? - Zowie
    • in-in-in-in - Artem
    • one
      "I've been sitting for several hours" - oh yeah ... You tried to type ... - Zowie

    I was looking for a solution to a similar problem, I got this option:

    Markup:

     <div class="menu-container"> <a class="menu" href="#">Меню</a> <ul class="dropdown" style="display: none;"> <li><a href="#">Подменю 1</a></li> <li><a href="#">Подменю 2</a></li> </ul> </div> 

    Code:

     jQuery(function($) { // В класс "page" обернуто все содержимое страницы. // Можно повесить событие и на body, но тогда это меню не будет работать на I-pad jQuery('.page').click(function( event ){ // проверяем находится ли элемент на который кликнули в нашем меню, // то есть в контейнере "menu-container" var eventInMenu = $( event.target ).parents('.menu-container'); // если родителя нет, значит клик был вне меню и меню сворачиваем if( !eventInMenu.length ){ $('.dropdown').hide(); } }); jQuery('.menu-container').click(function(){ $('.dropdown').show(); }); });