26

referring to Franek's question found here I have one more question.

The solution on the link above worked for me until I introduced another menu to my page. In this case, there are two menus next to each other. When I click on one of them, the relevant div is displayed showing possible options to select. Then, when I click on the document the div gets closed. But when I click on any other element it is still displayed.

A solution for me would be to run the code to close the menu on any other element click as well as document click.

How can I achieve this ?

(menu: invisible div element that when clicked on its title becomes visible)

Community
  • 1
  • 1
Subliminal Hash
  • 13,614
  • 20
  • 73
  • 104

3 Answers3

33

This is slightly better, as it also check the parent(s) of the element being clicked:

$(document).click(function(e) {
    var target = e.target;

    if (!$(target).is('#menu') && !$(target).parents().is('#menu')) {
        $('#menu').hide();
    }
});
Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
Anh
  • 6,523
  • 7
  • 46
  • 59
13

Clicking on every element but the menu that you want to hide right?

$(function() {
    $('*').click(function(e) {
        if(e.target.id != 'menu') {
            $('#menu').hide();
        }
    });
});
coma
  • 16,429
  • 4
  • 51
  • 76
-2

my html code is

<div class="filter-show">
    <ul style="display:none;">
        <li>menu 1</li>
        <li>menu 2</li>
        <li>menu 3</li>
    </ul>
</div>

and jquery code is

<script>
    $('html').click(function(event){
        if(!$(event.target).children().is('.filter-show > ul')){
            $(".filter-show > ul").fadeOut();
        }
    });
    $(".filter-show").click(function(){
        $(".filter-show > ul").fadeOut();
        $(this).children('ul').fadeIn();
    });
    $(".filter-show > ul").hover(function(){
        //
    },function(){
        $(".filter-show > ul").fadeOut();
    });
</script>
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
iman64
  • 1