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?
You might want to try something like this:
JS:
HTML:
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:
Fiddle: http://jsfiddle.net/maniator/46wuy/7/