Reputation: 283
I have a short JS code that should add and remove a class. The thing is, it adds a class but it never removes it. I can't find the problem. It should add and remove the class by clicking the same button.
$('.hamburger').on('click', function(){
if (!$(this).hasClass('opened')){
$(this).addClass('.opened');
$('.pop').css({'width' : '550px'});
$('.main').css({'margin-right' : '550px'});
}
else{
$(this).removeClass('opened');
$('.pop').css({'width' : '0'});
$('.main').css({'margin-right' : '0'});
}
});
Upvotes: 0
Views: 87
Reputation: 3462
Its because you were adding '.opened' instead of opened.
maybe look at the toggle function to clean up your code. also there's no point refetching the element on each run.
hopefully, this gives you a good idea on how to clean up and reduce repeating yourself.
const pop = $('.pop'),
main = $('.main'),
ham = $('.hamburger');
ham.on('click', toggleHamburger);
function toggleHamburger() {
toggleMainStyles(!ham.hasClass('opened') ? '550px' : 0);
}
function toggleMainStyles(value = 0) {
pop.css({ width: value });
main.css({ marginRight: value });
ham.toggleClass('opened');
}
.hamburger {
color: blue;
}
.opened {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hamburger">ham</div>
<div class="main"></div>
Upvotes: 1
Reputation: 66
Remove the "." in $(this).addClass('.opened'); ==> $(this).addClass('opened');
For the style class, you can also use toggleClass (http://api.jquery.com/toggleclass/)
Upvotes: 1
Reputation: 749
You needn't add the dot to the class string you pass to $(this).addClass so instead it should be:
$(this).addClass('opened');
Upvotes: 1
Reputation: 375
try to use toggleClass method of Jquery it will add or remove class .
$('.hamburger').on('click', function(){
$(this).toggleClass("main");
});
Upvotes: 1