0

How do I add and remove a class every time I click?

Original Code

HTML:

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

CSS:

.box{
  width: 100px;
  height: 100px; 
  background: blue;
}

I want to add:

.rounded {
  border-radius: 10px;
}

I know I have to use the click function on the box div, but I don't know how to add a class and remove it.

Answer:

Use the toggleClass

$(".box").click(function(){
   $(this).toggleClass("rounded");
});
Community
  • 1
  • 1
Jtwa
  • 143
  • 2
  • 12

4 Answers4

2

The other solutions are just switching between class(es). If you want to modify the existing one and add/remove values from it use this:

$('.box').css('border-radius','50px');

and to remove:

$('.box').css('border-radius', '');

Working example.

decho
  • 494
  • 1
  • 4
  • 9
1

Jquery can remove a class, however cannot alter any CSS in class:

$(target).addClass("myClass");
$(target).removeClass("myClass andThisOne removeSoManyClasses");

To overwrite a class the other way:

$("body").append("<style class='remove'>.box{/*many css*/}</style>");
$(".remove").remove();
Daniel Cheung
  • 4,779
  • 1
  • 30
  • 63
0

Yes its possible.
To add css class the syntax is,

$(selector).addClass(classname)

To removecss class the syntax is,

$(selector).removeClass(classname)

Working Fiddle

Krishanu Dey
  • 6,326
  • 7
  • 51
  • 69
0

You shouldn't have to do this. How about this approach instead...

.box{
  width: 100px;
  height: 100px; 
  background: blue;
}

.box.rounded {
  border-radius: 10px;
}

Then just toggle the "rounded" class with toggleClass.

$('.box').toggleClass('rounded');
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66