Reputation: 481
This script runs my drop-down menu by toggling the .open and .close classes on click. How can I close this drop-down menu when the user clicks outside of the menu?
<script>
$(document).ready(function(){
$("li").addClass("closed");
$("li.sel").on("click",function(e){
e.preventDefault()
});
$("#navi1 li").click(function(){
$("#navi1 li").toggleClass("open");
});
});
</script>
Upvotes: 1
Views: 2454
Reputation: 4521
Here is how I did it. Essentially, you need to call a function on any click event, and, for every menu, if the event does not occur within that menu or one of the menu's child elements, then the menu's close function is called. Of course, your close function will edit the class attribute instead of using the jQuery fade functions. As you can see, I have several menus called "subscribe", "about me", "about this website", etc. I hope this helps.
$(document).ready(function(){
// menu hide/show logic
var TOGGLE_SPEED = 100;
var subscribe_menu = $("#subscribe-container");
var about_me = $("#about-me-container");
var about_this_website = $("#about-this-website-container");
var filter_menu = $("#filter-menu-container");
var img_menu = $("#img-menu-container");
var menuList = [subscribe_menu, about_me, about_this_website, filter_menu, img_menu];
function hideMenu(menu){
menu.fadeOut(TOGGLE_SPEED);
}
function showMenu(menu){
menu.fadeIn(TOGGLE_SPEED);
}
function toggleMenu(menu){
menu.fadeToggle(TOGGLE_SPEED);
}
function hideOthers(e){
for (var i in menuList) {
var menu = menuList[i];
// check to see if the event target is the menu
// or one of its children
if (!menu.is(e.target) && menu.has(e.target).length === 0) { hideMenu(menu); }
};
}
function clickHandler(menu){
var e = $.Event("click");
e.target = menu;
hideOthers(e);
toggleMenu(menu);
}
$(document).click(function(e){
hideOthers(e);
});
$("#subscribe-tab").click(function(){
clickHandler(subscribe_menu);
return false;
});
$("#about-me-tab").click(function(){
clickHandler(about_me);
return false;
});
$("#about-this-website-tab").click(function(){
clickHandler(about_this_website);
return false;
});
$("#filter-tab").click(function(){
clickHandler(filter_menu);
return false;
});
$("#img-menu-button").click(function(){
clickHandler(img_menu);
return false;
});
});
Upvotes: 0
Reputation: 234
Something like this should work:
$('*').not('#navi li').click(function(){
$('#navi li').hide();
});
Upvotes: 0
Reputation: 6648
Have you tried
$("yourNavMenu").blur(function(){
// Add your close class
});
Upvotes: 1