Creative Juices Bo. Co.

Satisfy Your Thirst For Something Refreshing!

Determining An Elements Width And Height Using Javascript

Prototyping the Element's 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 Element. 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

Element.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

Element.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>

UPDATE: Thanks to Bryan, I realized that I was prototyping the Object. I have updated it to prototype the Element instead. This should be safer.