Determining An Elements Width And Height Using Javascript

Prototyping the Objects Dimensions

I was browsing through my utility scripts today and I came across these two little gems and I thought I would share them with you. These functions will determine an elements width or height and return it's value. Very useful if you ever plan on doing any animation or dynamic user interaction on your web page.

They were originally standalone functions, but I decided to prototype them as extensions of an Object. But if you need them as standalone, you should be able to convert them fairly easily.

Also, these functions might not work so well with images, they were designed to work with other BLOCK style elements.

Get Element Width

Object.prototype.getElementWidth = function() {
   if (typeof this.clip !== "undefined") {
      return this.clip.width;
   } else {
      if (this.style.pixelWidth) {
         return this.style.pixelWidth;
      } else {
         return this.offsetWidth;
      }
   }
}

Get Element Height

Object.prototype.getElementHeight = function() {
   if (typeof this.clip !== "undefined") {
      return this.clip.height;
   } else {
      if (this.style.pixelHeight) {
         return this.style.pixelHeight;
      } else {
         return this.offsetHeight;
      }
   }
}

Usage

...JavaScript...
window.onload=function() {
   var myBlock = document.getElementById('BigDiv');
   alert(myBlock.getElementWidth());
}
... HTML ...
<div id="BigDiv">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed...</div>

Have something to say? Leave a comment!

You don't have to be registered to leave a comment. Unregistered user's comments will be approved before going live.




You are currently posting as an unregistered user.
This means that your comment will be reviewed prior to going live. If you are a registered user, please . New user? No problem, register for an account, it's FREE! Benefits include, posting instantly, screen name protection, collaboration recognition, subscribe to article updates, and so much more!