Categories:

Cross browser function for retrieving global/external CSS properties

It's easy to combine IE's "currentStyle" object and Firefox's "getComputedStyle" method into one, harmonious cascaded CSS property finder. Some object detection plus use of the square bracket notation ([]) to reference a property is all that's needed:

<script type="text/javascript">

function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}

</script>

For those unaware, in JavaScript, you can access a property using one of two notations- the more common dot (.) notation, or the square bracket notation ([]). The later while more obtuse, has the advantage of enabling you to specify a property as a variable name (instead of string). It comes in handy in this case where the CSS property we want to look up is obviously dynamic. The "cssprop" parameter in the above function should be the desired CSS property to look up in camelCase convention (ie: "backgroundColor" instead of "background-color").

Lets go back to our familiar example again, this time, using our new cross browser function to retrieve the cascaded CSS property values of the element:

<head>
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
}
</style>
</head>

<body>
<div id="test">This is some text</div>

<script type="text/javascript">

function getStyle(el, cssprop){
 if (el.currentStyle) //IE
  return el.currentStyle[cssprop]
 else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
  return document.defaultView.getComputedStyle(el, "")[cssprop]
 else //try and get inline style
  return el.style[cssprop]
}

var mydiv=document.getElementById("test")

alert(getStyle(mydiv, 'width')) //alerts 100px
alert(getStyle(mydiv, 'backgroundColor')) //alerts yellow


</script>
</body>

And there you have it folks!