Thursday, February 4, 2010

Retrieve an element's width or height using JavaScript

Even though, not 100% browser independent, the following JavaScript code will get you an element's current/rendered width or height. The code is pretty simple and self-explanatory.

Code to retrieve element's width:
function getWidth(element){

    if (typeof element.clip !== "undefined") //netscape
    {
        return element.clip.width;
    }
    else {
        if (element.style.pixelWidth)//opera 
        {
            return element.style.pixelWidth;
        }
        else //IE and firefox
        {
            return element.offsetWidth;
        }
    }
}
Code to retrieve element's height:
function getHeight(element){

    if (typeof element.clip !== "undefined")    //netscape
    {
        return element.clip.height;
    }
    else {
        if (element.style.pixelHeight) //opera
        {
            return element.style.pixelHeight;
        }
        else //IE and firefox
        {
            return element.offsetHeight;
        }
    }
}
Sample Usage:
function usage(){
 alert(getWidth(document.getElementById("yourElementId")));
}
This code works for most of the input (dropdown/select-one/Select-multiple, textbox, textarea) elements in an HTML form. Feel free to share any better solutions.

2 comments:

  1. Even though, not 100% browser independent,

    wtf is this supposed to mean, WHICH BROWSERS DO NOT SUPPORT THIS

    ReplyDelete
  2. Haven't tested this with browsers like Chrome, Konqueror, Safari, Camino etc; didn't wanted to give a wrong idea that this will cover all browsers.

    If it is found working in any of these browsers, please share.

    ReplyDelete