Reputation: 418
I'm doing an accordion menu bar, problem is when i click a link without a children menu the links that has children are still opened, Can somebody help me on how to fix or improve my jquery, what i want is like.. If i click the link without child, all accordion are set to close.
function initMenu() {
$(".sub-menu").hide();
$('#accordion1 li a').click(
function () {
var checkElement = $(this).next();
if ((checkElement.is('ul')) && (checkElement.is(':visible'))) {
checkElement.slideUp('normal');
return false;
}
if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
$('#accordion1 ul:visible').not(checkElement.parentsUntil('#accordion1')).slideUp('normal');
checkElement.slideDown('normal');
return false;
}
});
$('.current-menu-item').parentsUntil('#accordion1').slideDown('normal');
}
$(function () {
initMenu();
});
$(function () {
var selector = '.menu li';
$(selector).on('click', function () {
$(selector).removeClass('active');
$(this).addClass('active');
});
$('.menu').delegate('li', 'click', function () {
$(this).addClass('active').siblings().removeClass('active');
});
});
here the JSFIDDLE
Upvotes: 0
Views: 219
Reputation: 29683
Add this in your click function at the top: WORKING DEMO
if($(this).parent().children('ul').length<1)
{
$('#accordion1 ul:visible').not(checkElement.parentsUntil('#accordion1')).slideUp('normal');
}
EDIT 1
Add this below code for the problem you mentioned in your comment:
if($(this).parents('ul').length>1 && $(this).parent().children('ul').length==0)
{
return;
}
Upvotes: 2
Reputation: 6722
This is my implementation of the same.
function initMenu() {
$(".sub-menu").hide();
$('#accordion1 li a').click(
function () {
var checkElement = $(this).next();
var allelems = $('#accordion1 li ul');
allelems.not(checkElement).slideUp('normal');
checkElement.slideDown('normal');
});
}
$(function () {
initMenu();
});
Upvotes: 0