Reputation: 3854
I've asked a similar question to this before and I've looked at several similar Q&As already but non of them suit my requirements (or I simply don't have the js knowledge to get them to work!).
I have a simple css/jquery menu set up which uses jQuery UI toggleClass to show and hide sub-menus.
I'd like to improve on this by closing any open sub-menu when another is clicked. Can anyone explain to me how to do this? Thanks.
Upvotes: 0
Views: 196
Reputation: 1898
$('#main-nav').hasClass('firstClass') ? $('#main-nav').addClass('SecondClass'): $('#main-nav').hasClass('firstClass');
Upvotes: 0
Reputation: 1979
A little slow on the response but it never hurts to have extra answers! Edit: This does have a slight performance gain as it's only running the $('#main-nav a.dd') selector once due to chaining. If you're not familiar, .end() cancels out the .next() by going to the previous selection.
$('#main-nav a.dd').next().addClass('navhidden')
.end().click(function() {
$('#main-nav a.dd').not(this).next().each( function() {
if ( !$(this).hasClass("navhidden") ) {
$(this).addClass("navhidden");
}
});
$(this).next().toggleClass('navhidden', 'fast');
return false;
});
Upvotes: 0
Reputation: 220136
Add this to your function:
$(this).parent().siblings().find('ul:not(.navhidden)').addClass('navhidden', 'fast');
Here's your fiddle, updated: http://jsfiddle.net/abKhH/1/
P.S. @Colin's solution also works, but I thing the above solution is a little nicer, since it opens and closes the panels simultaneously.
Upvotes: 2
Reputation: 597
I added a line to your jQuery that will make sure all the submenus are closed before opening the one that was clicked.
Upvotes: 0