3

I have a box without color. if the box is being click() it will addClass('.red') to make it red, and if click again the box color change to blue. they change alternatively. and I don't know how to make it.

Code

HTML

<div class='box'></div>

CSS

.box {          
    width: 250px;
    height: 100px;    
    border: 1px #000 solid;
}

.red {
    background: red;
}

.blue {
    background: blue;
}

Javascript

$('div').click(function() {
    $(this).addClass('red');
});

link of jsfiddle

1

4 Answers 4

17

Try with toggleClass like

$('div').click(function() {
    $(this).toggleClass("red");
});    

If you want to toggle 2 classes red and blue then use like

$('div').click(function() {
    $(this).toggleClass("red blue");
});
Sign up to request clarification or add additional context in comments.

6 Comments

yes this is what i want sir.. you got it. but i also want to change color from white to red and blue
Shouldn't the second parameter be a bool?
Sorry in hurry iam not going well..See my final ans now
See my answer for toggling red and blue.
only change to color blue
|
5

If you want to change from white to red, and then red to blue, you can't use toggleClass(). You'd have to write some simple conditions to decide which class to add:

$('div').click(function() {
    var $this = $(this);
    if ($this.hasClass('blue')) {
        $this.removeClass();
    } else if ($this.hasClass('red')) {
        $this.removeClass('red').addClass('blue');
    } else {
        $this.addClass('red');
    }
});

Here's a fiddle

If you only want to switch between the classes red and blue, just add one of the classes to the markup, so that you can toggle between them:

<div class="blue">Hello World!</div>

Then just use toggleClass():

$('div').click(function() {
    $(this).toggleClass('red blue');
});

Here's another fiddle

Comments

2

use hasClass()

.hasClass()

to check the assigned class, try something like this:

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

Comments

2

Working DEMO

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

Refer this API documentation for more about toggleClass

3 Comments

You have an extra closing bracket for your .blue.
@JGallardo Where? I don't see
in your demo. You have an extra closing bracket on the blue and actually the class is defined twice .blue { background:blue; } } .blue { background: blue; }

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.