Referencing CSS3 Properties Using JavaScript

By Rob Gravelle

Referencing CSS3 Properties Using JavaScript

7/16/13

 

Recently, I discussed using JavaScript's CSS3 Selectors in the article of the same name. But the CSS3 specification is far more reaching than that. Unlike CSS2, which is a large single specification defining various features, CSS3 is divided into several separate documents called "modules". Each module adds new capabilities or extends features defined in CSS2. In today's article, we're going to explore the latest and greatest ways to access CSS3 properties and their values.

Converting CSS Property Names To JavaScript

CSS3 has made more properties than ever accessible via JavaScript. In order to make the names comply with JavaScript naming conventions, CSS property names take on a different format than they do in stylesheets. Whereas CSS property names use lowercase along with hyphens to link words together, their javascript equivalents utilize camel case. Hence "background-color" becomes "backgroundColor", and "list-style-type" becomes "listStyleType". A single word property such as height remains as is.

Luckily, converting from CSS to JavaScript has limited applicability and is quickly becoming a thing of the past.

The HTMLElement Style Attribute

You can access any single CSS property of an element using the element's style attribute:

<div class="rounded-border">
This box has rounded borders.
</div>
<script language="JavaScript" type="text/javascript">
<!--
  var borderRadius = document.getElementById("RoundedDiv").style.borderRadius;
//-->
</script>

The above code is accessing the CSS3 border-radius property using the JavaScript naming convention. The border-radius property sets the amount of rounding on the elements corners. This works because the CSS was applied inline on the element. As we all (or at least most of us) have realized, having inline styles isn't a very good and efficient approach. So then we move all our CSS to an external file and suddenly the style property returns an empty string when checking it.

There are better and more modern ways of accessing CSS properties using the computed and current styles of the element.

The DOM getComputedStyle() Method

Most modern browsers support the DOM getComputedStyle() method. It provides access to the final computed style of any element within a document, including stylings from multiple sources and inherited ones. It accepts an element object and an optional string specifying a pseudo-element to match. It can be omitted or null for regular elements. getComputedStyle() returns a CSSStyleDeclaration object, which contains a number of methods pertaining to the CSS style. One of those is getPropertyValue(propertyName). It returns the property value for the given CSS property name. Here's an example:

var elem   = document.getElementById("container");
var height = getComputedStyle(elem).getPropertyValue("height");

The Element.currentStyle Property

The Element.currentStyle property is utilized by Internet Explorer to retrieve the cascaded style of an element. Cascaded style values are similar to computed values except that they aren't always returned in absolute values. For example, an element's width or height may be expressed as a percentage, such as 75%, compared to a computed value, which would be given in terms of pixels. Another difference between computed and current values is a cascaded width or height may have a value of "auto" if it is not specified in the CSS anywhere. Here's how to retrieve a CSS3 property value using the Element.currentStyle property:

var elem   = document.getElementById("container");
var height = oElm.currentStyle["border-radius"];  

The currentStyle accepts both CSS and JavaScript camel case naming so both oElm.currentStyle[border-radius] and oElm.currentStyle[borderRadius] are acceptable.

A Cross-browser Method

We can combine these two techniques into one method to support all major browsers by testing for window.getComputedStyle() or Element.currentStyle support:

function getStyle(oElm, css3Prop){
        var strValue = "";
  
  if(window.getComputedStyle){
                  strValue = getComputedStyle(oElm).getPropertyValue(css3Prop);
        }
  //IE
  else if (oElm.currentStyle){
    try {
                  strValue = oElm.currentStyle[css3Prop];
    } catch (e) {}
        }
        
        return strValue;
}

//call as follows
getStyle(document.getElementById("container"), "border-radius");

It is worth mentioning that the above code will return a value even if the style value was applied by shorthand in the CSS. For example, this will work just fine:

/* Element CSS*/
div#container{
        font: 2em/2.25em Verdana, Geneva, Arial, Helvetica, sans-serif;
  border-radius: 7.5em 5em;
}

<script language="JavaScript" type="text/javascript">
<!--
  var borderRadius = getStyle(document.getElementById("container"), "border-radius");  //sets borderRadius to "7.5em 5em"
//-->
</script>

One more difference between the getComputedStyle() method and currentStyle property is that trying to access an invalid CSS style on the latter will result in an error. That's why there is a try/catch block around line 10.

Setting CSS Style Property Values

If you're only modifying a single property, you can change the CSS setting directly using the element's style property. Just be sure to use camel case on the property name:

var elem = document.getElementById("container");
elem.style.borderRadius = "7.5em 5em;";

The Element.setAttribute() method supports one or more CSS values and uses the CSS naming style:

var elem = document.getElementById("container");
elem.setAttribute("style", "width: 500px; background-color: yellow; border-radius: 7.5em 5em;");

Conclusion

The content presented here today will work a good 90% of the time, cut be aware that certain CSS3 properties are unique to specific browsers, and are prefixed with a vendor extension to designate them as such. These are a little more challenging in JavaScript, but there are tricks for dealing with them. I`ll show you how next time.


If you enjoyed this article, please contribute to Rob's rock star aspirations by purchasing one of Rob's cover or original songs from iTunes.com for only 0.99 cents each.

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleWebDesign.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. EmailRob to receive a free estimate on your software project.

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His band, Ivory Knight, was rated as one Canada's top hard rock and metal groups by Brave Words magazine (issue #92).

Rob uses and recommends MochaHost, which provides Web Hosting at $3.10 per month, 2 LifeTime Free Domains, and 6 Months Free!



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date