This blog has moved, permanently, to

Friday, May 15, 2009

JavaScript Dimensions and Element Positioning

Now that the main browsers have (sort of) merged in terms of DOM element positioning, it's a lot easier to position your elements on a web page than it used to be. I still forget off-hand what is what, so here's a table of the document objects and their properties that are useful when writing dynamic element sizing and/or positioning.

Screen, Document and Element Sizes

The width and height of the user's screen e.g. 1440 x 900
The width and height of the user's screen excluding taskbars.
The actual width and height of the document (see blue arrow above).
The width and height of the document, not taking into account any scrolling (see red line above)
The width and height of an element. All style elements MUST be applied before getting this value, including display, visibility, etc.

Element Positioning

Unfortunately, getting an element position isn't quite as easy, due to different implementations in the browser. The following JavaScript function can be used to get the axt co-ordinates of an element within the document.

// gets the absolute position of an element on the screen
function getAbsolutePosition(element)
    var left = 0;
    var top = 0;
    // internet explorer
    if (element.offsetParent)
        while (element.offsetParent)
            left += element.offsetLeft
            top += element.offsetTop;
            element = element.offsetParent;
    // other browsers
    else if (element.x)
        left = element.x;
        top = element.y;
    return { x:left, y:top };
For example, if you have an element with id 'myElement':
var pos = getAbsolutePosition(document.getElementById('myElement'));
var left = pos.x;
var top = pos.y;

No comments:

Post a Comment

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