Adrian
Adrian

Reputation: 2012

jquery dropdown menu, toggling classes

I have a dropdown menu and am using jQuery to toggle classes when clicked on. So when I click <a> , its parent <li> becomes active, thus displaying its submenu using css. My problem is, the purpose of the RemoveClass here is so it will remove the active class in whatever submenu was already open.

The problem is when I click the <a> again, it doesnt close the current submenu, ie it doesnt seem to be toggling, just adding the class.

$("#pop-out-left ul li a").click(function () {
    $("#pop-out-left ul li").removeClass("active");
    $(this).parent().toggleClass("active");

    });

Here is the CSS..

#pop-out-left > ul > li.active > a + ul {
display: block;
}

Upvotes: 1

Views: 1449

Answers (1)

Mikael &#214;stberg
Mikael &#214;stberg

Reputation: 17156

This is because you start out with removing the active class on all li tags, using this code:

$("#pop-out-left ul li").removeClass("active");

And then when you toggle, the class gets added again. This means that the second click just repeats the first case.

To solve it, simply alter the statement above to exclude the item clicked, like so:

$("#pop-out-left ul li a").click(function () {
    $("#pop-out-left ul li")
        .not($(this).parent())
        .removeClass("active");
    $(this).parent().toggleClass("active");
});

Here is a working fiddle: jsfiddle.net/dDhYu

Upvotes: 1

Related Questions