JQuery: temporarily change the style, then reset to the original class

Say I have a class called testThing:

.testThing { background-color:#000000; float:left; height:50px; width:50px; } 

And I want to be able to test the background color change for any control of this class when a button is clicked:

 function setColor(someColor) { jQuery('.testThing').css('background-color', someColor); } 

But I want the user to be able to reset to the original color (another click of a button) depending on what class has:

 function resetClass() { jQuery('#currentColor').removeClass('testThing'); jQuery('#currentColor').addClass('testThing'); } 

It looks like this will work (Albiet is not the best way to do this), but the background color of the control will not reset to the original value contained in this class.

Now either I need to find out why it is deleted, and not reset, or just an easy way to do it ... seeing that it seems silly to delete and read the class ...

+50
jquery css
Jun 27 '09 at 19:05
source share
4 answers

Jquery adds CSS to the style attribute, which takes precedence over what's in your CSS file. You do not modify your CSS document with this function, and so adding and removing and adding a class has no effect, as it has not been modified at all!

You should use the same function, but this time set the background color to black.

 function reset(this) { $(this).css('background-color', '#000000'); } 

Or just remove the style attribute

 function reset(this) { $(this).removeAttr('style'); } 
+68
Jun 27 '09 at 19:08
source share

I know this is old, but you can just set the value to an empty string to remove your own style as follows:

 // set $(this).css('background-color', '#000000'); // reset $(this).css('background-color', ''); 
+99
May 7 '10 at
source share

What about toggleClass("testThing") ? I use it when changing more than one property.

http://api.jquery.com/toggleClass/

+4
Oct 11
source share

It's better to just add another class that overrides the style you want to change, and then delete it. It surpasses the hard coding style information inside js. The only problem is that you have to ensure that the added class is of a higher order, so that the element takes the style from it, and not the existing class, but it is not difficult.

+2
Jun 27 '09 at 20:01
source share



All Articles