How to deselect a div after adding a class

61 Views Asked by At

Pls see:

https://jsfiddle.net/villete/0yf0nucj/

$(document).ready(function(){            
    $('.block').click(function() {
        $(".block.blockActive").removeClass("blockActive");
        $(this).addClass('blockActive');
    });
});

How do I deselect the blue div so that none of the divs are selected anymore? I think I need a toggle for this but I dont know how to implement this.

Thank you :-)

2

There are 2 best solutions below

2
On BEST ANSWER

Okay, I think I got the solution.

    if (!$(this).hasClass('blockActive')) {
        $('.block').removeClass('blockActive');
        $(this).addClass('blockActive');
    } else {
        $(this).removeClass('blockActive');
    }

https://jsfiddle.net/0yf0nucj/8/

Found it here

0
On

I think toggleClass("blockActive") is what you are searching for.