background top

Looking up CSS Styles in JavaScript

This can be extremely useful in the event you have a toolbar, menu, or custom piece of code that is changing styles on the fly. We had a need to look up CSS Styles affecting an object on our page with JavaScript.  Unfortunately, it’s not as easy as document.getElementById(‘myobject’).style.background.  If you want to get the CSS styles that have been set by other JavaScript code, you’ll need to use this function to look up those styles.  Let’s say you want to put a div at the top of the page, but doing so would break the background styles on the body.  You can look up those styles, make an adjustment for the height of your div and then display it.

One thing to note is that IE and Firefox (as well as other W3C standards browsers) use a different function to accomplish this.  The W3C standard function is “getComputedStyle” whereas IE uses the proprietary “currentStyle”.

A working script for IE and Firefox is below:

getstylebanner = function(prop, element) {
    if (element.style[prop]) {
        return element.style[prop]; /* if its an inline style in IE */
    }
    else if (element.currentStyle) {
        return element.currentStyle[prop]; /* if its style set in IE */
    }
    else if (document.defaultView && document.defaultView.getComputedStyle) { /* Firefox */
        prop = prop.replace(/([A-Z])/g, "-$1");
        prop = prop.toLowerCase();
        return document.defaultView.getComputedStyle(element, "").getPropertyValue(prop);
    }
};

An example of looking up the top margin on the body of your page:

var marginTop = getstylebanner('marginTop', document.body);
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Reddit
  • TwitThis

Leave a Reply