How can I access a property from a CSS class by jQuery? I have a CSS class like:
.highlight {
color: red;
}
And I need to do a color animation on an object:
$(this).animate({
color: [color of highlight class]
}, 750);
So that I can change from red
to blue
(in the CSS) and my animation will work in accordance with my CSS.
One approach would be to place an invisible element with the highlight
class and then get the color of the element to use in the animation, but I guess this is a very, very bad practice.
Any suggestions?
I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.
There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.
If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).
I only tested on jsFiddle with some weak test cases, let me know if this works for you.
example usage:
edit:
I neglected to take into consideration grouped rules. I changed the selector check to this:
now it will check if any of the selectors in a grouped rules matches.
Here's another method: add a hidden div with the class applied. Use jQuery.css to look up the style value. Then remove the element.
http://plnkr.co/edit/Cu4lPbaJWHW42vgsk9ey
Why don't add
.highlighted
class, cache thecolor
style, than remove it and animate to cached color? I.e. don't append elements and don't parse & loop styles.jsfiddle example
Since you are already using jQuery try using the jQuery-ui's function
switchClass
which would allow you to animate to this new color.For example:
Demo
In case you do not want to include the whole UI library here is the code they use:
And the animateClass fn:
Working fiddle with all the functions that are needed: http://jsfiddle.net/maniator/3C5ZQ/
How about this?
It's kind of dirty but will give you an (empty) element to reference to get the CSS value for which you are looking.
Update Here is a decent solution from CSS parser/abstracter? How to convert stylesheet into object
Usage
Here is a fiddle http://jsfiddle.net/wzXDx/1/. I had to use
styleSheets[1]
to get this to work in the fiddle due to the embedded nature of the environment.Unfortunately I can't comment on this awesome answer, but found a case that isn't catered for (when CSS class is declared multiple times and the first declaration doesn't have the style you're looking for), made a jsFiddle to cater for it:
Also took out the split in the conditional, not necessary and now it confirms that the style is present in the rule being checked.
Just for shigiggles created a jsFiddle to cache the styles by selector:
Although if you do use that, I would suggest putting it in a closure/class. Thanks again to rlemon for the awesome original.