Reputation: 4363
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
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 aside
s. 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