Caspert
Caspert

Reputation: 4363

Toggle class will not close my sidebar after clicking the second time

I use the following jQuery to toggle between an class. It will add open when toggle-sidebar is clicked and close the other ones on the page, but I can't close the current one if I click the second time when I want to close the sidebar.

My code:

$('.toggle-sidebar').click(function(event) {
            event.preventDefault();
            $('section aside').removeClass('open');
            $(this).parent().find('aside').toggleClass('open');
        }); 

Upvotes: 0

Views: 354

Answers (1)

u_mulder
u_mulder

Reputation: 54796

So:

$('section aside').removeClass('open');

removes open class from all aside even from current. So it doesn't have an open class now.

And this

$(this).parent().find('aside').toggleClass('open');

adds open class to current aside. So you in fact don't have codes for removing open class from current aside.

I think you should check: if current aside has open class - then only remove it, otherwise - add and remove from other asides. Kinda:

$('.toggle-sidebar').click(function(event) {
    event.preventDefault();
    var aside$ = $(this).parent().find('aside');
    if ( aside$.hasClass('open') ) {
        aside$.removeClass('open');
    } else {
        $('section aside').removeClass('open');
        aside$.addClass('open');
    }
}); 

Upvotes: 1

Related Questions