JavaScript: getting CSS width and height values

Sometimes we have to get the dimensions of an element when they're defined in our CSS styles. Unfortunately, the style object attached to every element doesn't work in this case, because it can only handle inline styles. Instead, we should get the actual computed styles of an element. Since Internet Explorer uses the currentStyle property and all other W3C DOM compliant browsers implement the getComputedStyle() method, we have to write the following function, popularized by Peter-Paul Koch:

function getCSS(element, property) {

  var elem = document.getElementById(element);
  var css = null;
  
  if(elem.currentStyle) {
  
    css = elem.currentStyle[property];
  
  
  } else if(window.getComputedStyle) {
  
  
     css = document.defaultView.getComputedStyle(elem, null).
           getPropertyValue(property);
  
  }
  
  return css;



}

So if we have the following styles:

#test {
 width: 100px;
 height: 100px;
}

we get the following values:

alert(getCSS('test', 'width')); // 100px
alert(getCSS('test', 'height')); // 100px

We have a trailing px token that we can remove using the parseInt() function to get the absolute values instead:

var width = getCSS('test', 'width');
var height = getCSS('test', 'height');
  
alert(parseInt(width)); // 100
alert(parseInt(height)); // 100

Leave a Reply

Note: Only a member of this blog may post a comment.