0

I have found a couple topics regarding to this issue, but none of them unfortunately worked out for me. I am using this jQuery method like this:

//jQuery
$('.menu_user').click(function(){
    $(".top_menu").toggle();
});
// HTML
<div class="menu_user">MENU</div>
<nav class="top_menu">
  ...
</nav>

Basically, when I click on the MENU div, the menu is rolled down, when I click on it again, then the menu is rolled up = hidden. The problem is that when the menu is rolled down and I click outside the Menu div, the menu stays displayed - and I would like to hide it.

I went through some tutorials, but I didn't find a solution that would solve this issue.

I'll be glad for every help regarding to this issue.

Thanks!

Emre Erkan
  • 8,433
  • 3
  • 48
  • 53
user984621
  • 46,344
  • 73
  • 224
  • 412
  • possible duplicate of [How to detect a click outside an element?](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – Ram Jan 26 '14 at 14:25
  • Maybe jQuery .focus() .blur()? – TimSPQR Jan 26 '14 at 14:31

2 Answers2

0

You could use

$(document).on( "click", function() {

    if ($('.top_menu:hover').length === 0) {
        //hide the stuff
        //roll up menu
         $(".top_menu").hide();
    } else if ($('.menu_user:hover').length === 0) {
         $(".top_menu").toggle();
    }

});

so that when the menu is rolled down and the user clicked outside .top_menu it will roll up .top_menu

Remember that the above code will fire every time a user clicks on the page.

Jo E.
  • 7,822
  • 14
  • 58
  • 94
  • `Remember that the above code will fire every time a user clicks on the page.` -- that's sort of "terrible". I'd like to try to found a more elegant solution, there's no way to handle this with using methods related to `toggle()`? – user984621 Jan 26 '14 at 14:42
  • @user984621 you should not use `toggle()` in the above code because if you use toggle everytime a user clicks something on the screen the menu will be opening and closing. So we use `hide()`. Its actually not "terrible" even if a user makes 60 clicks per second since its such a very small piece of code. it just hides `.top_menu` if its open or toggles it if `.menu_user` is clicked. And it is how others do it. – Jo E. Jan 26 '14 at 14:49
0

You can do a click event, and inside it check if the click was inside the menu_user div. If not, then you can hide the dropdown.

$("body > div").click(function() {
    if ($(this).attr("class") != "menu_user") {
       $(".top_menu").hide();
    }
});
Omri Aharon
  • 16,959
  • 5
  • 40
  • 58