user1428033 user1428033 - 6 months ago 40
Javascript Question

jQuery accordion menu: Setting active class

I have an accordion menu:

<ul id="menu">
<li>
<a href="#" class="highmenu">Menu1</a>
<ul class="sub">
<li class="submenulink">Menu1Link1</li>
<li class="submenulink">Menu1Link2</li>
</ul>
</li>
<li>
<a href="#" class="highmenu">Menu2</a>
<ul class="sub">
<li class="submenulink">Menu2Link1</li>
<li class="submenulink">Menu2Link2</li>
</ul>
</li>
</ul>


And here's the jQuery script I'm using:

$(document).ready(function() {
var pathname = window.location.pathname;
$("#menu ul").hide();
$("#menu a[href='" + pathname + "']").parents(".sub").show();
$("#menu li a").click(function() {
var checkElement = $(this).next();
if ((checkElement.is("ul")) && (checkElement.is(":visible"))) {
return false;
}
if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
$("#menu ul:visible").slideUp("normal");
checkElement.slideDown("normal");
return false;
}
});
});


What I would like to have is that when particular sub is open, the corresponding highmenu will be set to
highmenu active
class and when sub is hidden, the active class will be removed.

Any help will be greatly appreciated, thanks!

Answer

How about this. Every time you click on a link remove all active class from all links then apply it to only the appropriate one:

var pathname = window.location.pathname;
$("#menu ul").hide();
$("#menu a[href='" + pathname + "']").parents(".sub").show();
$("#menu li a").click(function() {

    $("#menu li a").removeClass("active");
    $(this).addClass("active");

    var checkElement = $(this).next();
    if ((checkElement.is("ul")) && (checkElement.is(":visible"))) {
        return false;
    }
    if ((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        $("#menu ul:visible").slideUp("normal");
        checkElement.slideDown("normal");
        return false;
    }
});‚Äč

Working fiddle here: http://jsfiddle.net/jKGNA/

Comments