jQuery: toggleClass instead of addClass

jQuery 4 February 2016 | 5,464 Comments

Sometimes you need to add a class in a div, if you click on the button on the first time. For the second time you want to remove the added class. Normally you would check, if there is already the disered class in a if condition and use addClass() or removeClass(), like that:

$("selector").click(function(){
 if ($('selector').hasClass('class')){
    $('selector').removeClass('class');
 } else {
    $('selector').addClass('class');
 }
});

But there is a better way: Use the function toggleClass()

$("selector").click(function(){
    $('selector').toggleClass('class');
});

If your class exist, the function will remove it. If there is not the class, it will automatically added. It’s so easy ;-)


Fatal error: Allowed memory size of 57671680 bytes exhausted (tried to allocate 71 bytes) in /home/.sites/142/site754/web/wp-includes/comment.php on line 756