Reputation: 265
I am using the following for a dropdown menu. It works great, however, I can't figure out how to get an open dropdown to slideUp if somewhere in the body is clicked, or another dropdown is clicked.
$(document).ready(function () {
$('.nav li').click(function() {
var slideToggle = this;
if ($('ul', this).is(':visible')) {
$('ul', this).slideUp(function() {
$(slideToggle).removeClass('active');
});
}
else {
$('ul', this).slideDown();
$(slideToggle).addClass('active');
}
});
});
View it action here: http://jsfiddle.net/Ngh5C/1/
What would be the easiest way to go about what i've asked?
Upvotes: 1
Views: 600
Reputation: 45135
Take advantage of event bubbling and bind a click handler to a suitable parent container (e.g. body). Check the target in the handler and if it isn't one of your menus, use a selector to find the open menu and close it.
Here's a simple example as a starting point:
Try this fiddle to keep only one open at a time:
If you really only want to close the neighbors of the item clicked (which is an odd requirement), then this works:
Upvotes: 2