Reading style info with JavaScript

<![CDATA[Part of the online game I'm now developing (which needs a name – I was thinking of "Cash City Wars") requires some Javascript that alters the style of a DIV and then puts it back as it was. Changing the style is easy. For example to make the text green:

// Some code to get the DIV object and  store it in obj. = "green";

Storing the old style information is a little difficult. I tried:

obj.oStyle =; = "green";

But that didn’t work for two reasons: firstly objects are passed by reference so oStyle always contained the same thing as style. And secondly style (when used for reading) only contains explicitly set properties. So if you set width and left you’d still have to work out right yourself.

I found out there is another property you can use, getComputedStyle. This has it’s own little quirks however. Firstly it isn’t an method of the object, but used more like a function and secondly it doesn’t seem to work in IE6.

Firefox (W3 DOM):

temp = document.defaultView.getComputedStyle(obj, "");



I personally think the IE way makes more sense in this case but we have to cope wtih both. One thing that is slightly awkward is that one is a function the other is an array. So to make a simple to use interface to the correct function, we can use Javascript’s ability to use functions as first class objects (which means you can assign them to variables):

if (document.defaultView) {
    var cStyle = function(obj, prop) {
        var temp = document.defaultView.getComputedStyle(obj, "");
        return temp.getPropertyValue(prop);
} else if (document.body.currentStyle) {
    var cStyle = function(obj, prop) {
        return obj.currentStyle[prop];

You can now call cStyle like a normal function to get the computed value of any style property of any object.

Javascript, ECMAScript, DOM, code, programming, tutorial, code sample]]>


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s