So, I’m creating a submenu by myself by following the jQuery codex only and I got stuck. Everything else is perfect, though.
I have an HTML structure like the following:
<li><a href="#">smth</a>
<ul>
<li><a href="#">smth sub</a></li>
</ul>
</li>
<li><a href="#">smth</a>
<ul>
<li><a href="#">smth sub 2</a></li>
</ul>
</li>
And let’s say that the first SMTH is opened. Now, when I click on the second SMTH it will just appear on top of the other one.
My jQuery code is as follows.
$(document).ready(function() {
/*
* header navigation
*/
// hide sub UL's
$('ul.sub').hide();
$('#header .left li.m:first a, #header .right li.m:first a').css('borderLeft', 'none');
$('#header .left li.m:last a, #header .right li.m:last a').css('borderRight', 'none');
// Add class closed, because it's nessesery.
$('#header .left li ul').addClass('closed');
// If LI element is clicked, open or close sub UL?
$('#header .left li').click(function(event)
{
// If sub UL is closed, we need to open it.
if( $(this).find('ul').hasClass('closed') )
{
$(this).find('ul').removeClass('closed');
$(this).find('ul').addClass('opened');
$(this).find('ul').fadeIn('100');
}
// If sub UL is opened, we need to close it.
else
{
$(this).find('ul').removeClass('opened');
$(this).find('ul').addClass('closed');
$(this).find('ul').fadeOut('100');
}
});
});
I’m not entirely sure I got the image right, because I don’t know how you’re styling your menu, so I’ll assume it’s a vertical list of SMTHs with sublists showing to the right.
What you want to do is close all opened sublists (this will normally be only one sublist) when you click on the SMTH, before you add the “opened” class.
This is how I’d modify your code:
Also, Ben Roux’s switchClass advice is great, you should consider it.