t3chb0t
t3chb0t

Reputation: 18665

How to get a style property from a css class and set it to another css class?

Is it somehow possible to get a style property from a css class that is not used anywhere?

I'd like to read for example the color property that I want to apply to an animation with jquery ui but I want to avoid duplicating them again in the js code.

Let's say I have this:

.default-style {
   color: red;
}

.disabled-style {
   color: gray;
}

.current-style {}


<span class="current-style">Hello world!</span>

Now I would like to set the .default-style color to the .current-style and then animate the color from the .default-style to the .disabled-style and back on click but I don't know how to get them without creating a hidden element.

var currentColor = ""; // I'm stuck here. Get color from css class?
$("span.abc").animate({ color: currentColor });

Upvotes: 0

Views: 94

Answers (2)

Correct Way ! Without cheating the document

var currentColor;
var styleSheets = document.styleSheets;
for(var j=0; !currentColor && j<styleSheets.length; j++)
{
    var styleSheet = styleSheets[j];
    var cssprops = styleSheet.cssRules || styleSheet.rules; // .rules is for older IE
    for (var i = 0; i < cssprops.length; i++) {
        if(cssprops[i].selectorText == '.default-style');
            currentColor = cssprops[i].style.getPropertyCSSValue('color').cssText;
    }
}
$("span.abc").animate({ color: currentColor });

Reference From https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074266

You can cheat by creating an element, applying the class, adding the element to the document, getting its color, then removing it. If this is all done in one code block, the user will never see the element:

var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();

Alternately, you can loop through document.styleSheets in the document, and loop through the rules of each stylesheet looking for the one that uses that simple class selector, then look at the styles that rule defines.

Gratuitous snippet: ;-)

var div = $("<div>").addClass("default-style").appendTo(document.body);
var color = div.css("color");
div.remove();
$("<p>The color is: " + color + " (the color of this paragraph)</p>").css("color", color).appendTo(document.body);
.default-style {
   color: red;
}

.disabled-style {
   color: gray;
}

.current-style {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="current-style">Hello world!</span>


Side note: jQuery's animate function doesn't animate colors natively, you need to add a plugin to do it (jQuery UI bundles one, but if you're not using jQuery UI, you can just use one of the plugins that does this, such as this one, directly).

Upvotes: 1

Related Questions