heymrcarter
heymrcarter

Reputation: 678

hide submenu on body click

In my navigation the user clicks a link to open a submenu. as it stands the submenu stays open until it's parent link is clicked again. I'd like to have it so if the user clicks anywhere on the page but inside the submenu that the submenu hides.

The code i'm trying to get to work is:

for(var i=0; i<$('#topNav ul li').length; i++){
    if(openMenu[i] == 1){ 
        //i use an array to keep track of which submenu is open
        //all 'closed' or hidden submenus are assigned a value of 0 in the array,
        //the open submenu gets a value of 1
        $('body').not('#submenu'+i).click(function(){
            $('#submenu'+i).hide();
        });
    }   
}

the problem is nothing happens when i click on the body. I've set up a basic example on jsfiddle, it's here.

is there something i'm missing? can you not use the body tag as a selector for click events?

Upvotes: 0

Views: 1630

Answers (2)

morgar
morgar

Reputation: 2407

I think you are not follow the right path. When user click on body, all menus must be closed, so, you don't need to specify what is the open menu, just close all by calling to $('#topNav ul li').hide() (not sure how is your markup).

In order to avoid that clicking the open menu bubbles the click to the body, you should bind click to it an cancel the click:

$(clicked_menu).click(function(event) {
    event.stopPropagation();
});

Upvotes: 1

Naftali
Naftali

Reputation: 146310

You might want to try something like this:

JS:

$(function(){
    var visible = false;
    $('button').click(function(e){
        $('.menu').hide();
        var $ref = $(this).attr('ref');
        $('#menu'+$ref).show();
    });
});

HTML:

<div class='menu' id='menu1' style='background-color:#f00;'></div>
<div class='menu' id='menu2' style='background-color:#ff0;'></div>
<div class='menu' id='menu3' style='background-color:#f0f;'></div>
<button ref='1'>Click Me 1</button>
<button ref='2'>Click Me 2</button>
<button ref='3'>Click Me 3</button>

Fiddle: http://jsfiddle.net/maniator/46wuy/4/

This reduces the need to have a for loop on every click

EDIT
To address your comment below:

$('*').click(function(e){
     e.stopPropagation();
    if($(e.currentTarget).not($('.menu, button')).length  > 0){
         $('.menu').hide();
    }
});

Fiddle: http://jsfiddle.net/maniator/46wuy/7/

Upvotes: 1

Related Questions