Showing posts with label calculate. Show all posts
Showing posts with label calculate. Show all posts

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.