Reputation: 11
So, I have a simple menu: when you click on ONE shows the ONE ITEMS, when you click on TWO shows the TWO ITEMS. The ONE and TWO have a toggle function, so they slides down and up on click, but when i toggle TWO without closing ONE, things get messy.
$(function() {
$('li.sub', '#navigation').each(function() {
var $li = $(this);
var $div = $('div.submenu', $li);
var top = $li.height();
$li.toggle(function() {
$div.css('top', top).
slideDown('slow');
},
function() {
$div.
slideUp('slow');
});
});
});
a fiddle: http://jsfiddle.net/vGSWm/2/
Upvotes: 1
Views: 194
Reputation: 146191
You may try this
$(function() {
$('#navigation li.sub').click(function(e) {
var el = $(this).find('.submenu');
$('.submenu').not(el).slideUp(function(){
el.slideToggle();
});
});
});
Update :
$(function() {
$('#navigation li.sub').click(function(e) {
var el = $(this).find('.submenu');
if(el.hasClass('open'))
{
el.slideUp(function(){
el.removeClass('open');
});
}
else
{
var opened = $('.submenu.open');
if(opened.length)
{
opened.slideUp(function(){
opened.removeClass('open');
el.slideToggle(function(){
el.addClass('open');
});
})
}
else
{
el.slideToggle(function(){
el.addClass('open');
});
}
}
});
});
DEMO.
Upvotes: 2
Reputation: 535
To solve this problem, you need to programatically trigger the toggle on any of the list items that are already open.
The easiest way to do this is to add in code before you show the div for the menu that has just been clicked to hide all of the divs.
For example edit the function so it reads:
$li.toggle(function() {
$('div.submenu:visible').parent('li.sub').click();
$div.css('top', top).
slideDown('slow');
},
This solution presumes that you may want to have more than two list items and will scale for any number. If you know that you will only ever have two list items you can call the list item directly.
Upvotes: 1