spencer.sm
spencer.sm

Reputation: 20526

Three way toggle to add and remove classes in jQuery

I'm trying to get multiple divs with the class 'box' to switch between three classes: 'box', 'box black', and 'box blue' when I click on them. Something isn't quite working with how I have it set up. Thanks for your help!

$('.box').click(function () {
    if ($(this).class == 'box') {
        $(this).addClass('black');
    } else if ($(this).class == 'box black') {
        $(this).removeClass('black');
        $(this).addClass('blue');
    } else if ($(this).class == 'box blue') {
        $(this).removeClass('blue');
    }
});

Upvotes: 1

Views: 177

Answers (2)

wrxsti
wrxsti

Reputation: 3504

Your element always has the class .box so it will always trigger the initial condition. Try added a secondary initial class like this: DEMO

HTML

<div class="box none"></div>

jQuery

    $('.box').click(function () {
        if ($(this).hasClass('none')) {
            $(this).removeClass('none');
            $(this).addClass('black');
        } else if ($(this).hasClass('black')) {
            $(this).removeClass('black');
            $(this).addClass('blue');
        } else if ($(this).hasClass('blue')) {
            $(this).removeClass('blue');
            $(this).addClass('none');
        }
    });

CSS

   .box {
        border: solid 1px;
        width: 100px;
        height: 100px;
        background: #fff;
    }

    .black {
        background: #000;
    }
    .blue {
        background: blue;
    }

Upvotes: 2

Barry
Barry

Reputation: 3723

Try

$('.box').click(function () {
    if ($(this).hasClass('box')) {
        if ($(this).hasClass('black')) {
            $(this).removeClass('black').addClass('blue');
        } else if ($(this).hasClass('blue')) {
            $(this).removeClass('blue');
        } else {
            $(this).addClass('black');
        }
    }
});

First you check if the element has class box. If so, you toggle between the second classes (black, blue an no class).

Upvotes: 0

Related Questions