jQuery: Temporarily change a style then reset to original class

JqueryCss

Jquery Problem Overview


Say I have a class named testThing:

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

And I want to be able to test a background color change to whatever control is of that class on a button click:

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

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

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

Seems like this would work (Albiet not the best way to do this) but the control's background color doesn't reset to the original value held in that class.

Now either I need to figure out why that remove to add doesn't reset it OR just a plain better way of doing it... seeing as it seems silly to remove and readd the class...

Jquery Solutions


Solution 1 - Jquery

I know this is old, but you can just set the value to an empty string to remove your custom style like so:

// set
$(this).css('background-color', '#000000');

// reset
$(this).css('background-color', '');

Solution 2 - Jquery

Jquery adds CSS in the style attribute which has higher priority over what is in your CSS file. You're not changing your CSS document with that function and thus adding and removing and adding the class have no effect since it hasn't been modified at all!

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

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

Or simply remove the style attribute

function reset(this)
{
  $(this).removeAttr('style');
}

Solution 3 - Jquery

What about toggleClass("testThing")? I use it when there's more than one property to change.

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

Solution 4 - Jquery

It is better to just add another class that overrides the style you want to change and then remove it. It beats hard coding style info inside the js. The only issue is youll have to ensure the added class is of a higher order so that the element takes the style from it rather than the existing class but this is not hard to ensure.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionProgrammin ToolView Question on Stackoverflow
Solution 1 - JqueryjscheelView Answer on Stackoverflow
Solution 2 - JqueryGab RoyerView Answer on Stackoverflow
Solution 3 - JqueryAlexandraView Answer on Stackoverflow
Solution 4 - JqueryredsquareView Answer on Stackoverflow