user1836025
user1836025

Reputation: 209

current dropdown won't close after opening

I have this script that opens dropdowns under my navigation items.

Right now, when a navigation item is clicked, the drop down will open. When I click the same item again it will not close.

I am able to close it only if I click on another navigation item to open another dropdown.

How can I get the current navigation item to close when I click it, while keeping the functionality of it closing when other navigation items are clicked?

$("li.dropdown-control > a").click( function (event) {
    event.preventDefault()
        $('.dropped').removeClass('dropped');
        var nextSibling = $(this).next();
        nextSibling.toggleClass("dropped");  
});

Upvotes: 2

Views: 597

Answers (2)

user2004812
user2004812

Reputation:

Try this by removing $('.dropped').removeClass('dropped'); line from your code. toggleClass means add class if not added, or remove class if it has been added.

Now, by removing $('.dropped').removeClass('dropped'); toggleClass will remove .dropped class

$("li.dropdown-control > a").click( function (event) {
    event.preventDefault()
        var nextSibling = $(this).next();
        nextSibling.toggleClass("dropped");  
});

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92983

Looking at your code:

    $('.dropped').removeClass('dropped');
    var nextSibling = $(this).next();
    nextSibling.toggleClass("dropped");  

this will remove ALL the dropped classes (including the one you just clicked on, if it's already dropped open) and then add it back to the same element. That's why it never seems to close -- you actually close and open it again immediately.

Try this instead:

    var nextSibling = $(this).next();
    nextSibling.toggleClass("dropped");  
    $('.dropped').not(nextSibling).removeClass('dropped');

Upvotes: 2

Related Questions