Search code examples
jquerytoggledeselect

How to deselect a div after adding a class


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 :-)


Solution

  • 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