1

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');
    }
});
4
  • 3
    use .hasClass() instead of .class to check whether the element has that class or not! Commented Jun 5, 2015 at 16:55
  • @DhavalMarthak With the .hasClass() instead of class it almost works... I just gets stuck on the black and doesn't change to blue. jsfiddle here . Commented Jun 5, 2015 at 17:04
  • It's because your code will always fire first if condition and will addClass black to the clicked div! Commented Jun 5, 2015 at 17:09
  • 1
    See this i've made changes in css too! I hope you needed this. Commented Jun 5, 2015 at 17:10

2 Answers 2

2

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;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.