AntonAL
AntonAL

Reputation: 17410

Get CSS declarations with JavaScript

i'm writing a sophisticated visual effect, that changes "box-shadow" property.

Let's for short, just name the value for shadow (1pt 1pt 3pt rgba(...)), like "shadow".

I have a stylesheet, and HTML element in question.

Element has, say, "shadow1" value defined for normal state, and "shadow2" for hovered state:

.elem {
    box-shadow: #333 1pt 1pt 3pt; /* shadow1 */
 }
.elem:hover {
    box-shadow: #666 3pt 3pt 5pt; /* shadow2 */
 }

My script adds it's own shadow to existing one. So:

box-shadow: shadow1, shadow2

This is simple to implement. I just need to do following, using jQuery:

var defaultShadow = elem.css("box-shadow");
elem.css("box-shadow", defaultShadow + ", " + anotherShadow);

So, the algorithm is following:

  1. var defaultShadow = elem.css("box-shadow");
  2. Do something in a setInterval. Add another shadow to default one

The problem arises, when element gets hovered, having effect-script running. In this case, effect is already working with "defaultShadow", that was obtained in step 1.

It's more harder, because shadows, stated in script appears in the "style" attribute, and all rules, declared with external CSS are getting overridden.

Is there a way to get CSS styles, declared in a .css file, for element in question, using JavaScript. I need also styles for states of the element, like ":hover", ":active" etc.

Upvotes: 1

Views: 2601

Answers (2)

Phani CR
Phani CR

Reputation: 97

document.getElementById("id").className = 'arrow_box

Upvotes: 0

Mark Coleman
Mark Coleman

Reputation: 40863

Is there a way to get CSS styles, declared in a .css file, for element in question, using JavaScript. I need also styles for states of the element, like "hover", "active" etc.

You should be able to modify the cssRules object with javascript to create your own rules instead of relying on inline styles.

See this blog post for a bit more information.

Example of IE:

document.styleSheets[0].addRule("p .myclass", "font-size: 120%");

Example for Firefox:

document.styleSheets[0].insertRule("p{font-size: 20px;}", 0);

Reference doc these were found.

Upvotes: 3

Related Questions