I am trying to toggle a sidebar, but it works only once. I think the query code is self explanatory. Though I can write the HTML code if you want.
$('.side-menu').on('click', function(){
$('.control-sidebar').addClass('active-sidebar');
$('.side-menu').on('click', function(){
$('.control-sidebar').removeClass('active-sidebar');
});
});
A clean code solution would look somehow like this:
$('.side-menu').on('click', function(){
$('.control-sidebar').toggleClass('active-sidebar');
});
I think the logic is not right in your case.
if(!$('.control-sidebar').hasClass('active-sidebar')){...}
This code will run when class "control-sidebar" don't have class "active-sidebar".
at the beginning, the case happens so you can click on .side-menu and add class "active-sidebar" to DOM. this against your first logic.
Moreover, why this happens twice in your code?
$('.side-menu').on('click', function(){...}
Solution: Use toggle class: see this https://jsfiddle.net/BeklievParviz/rwnpk0wm/
$('.side-menu').on('click', function(){
$('.control-sidebar').toggleClass('active-sidebar');
});
User This
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.