Archive

Archive for September 28, 2006

Javascript: Calculate Element Position

September 28, 2006 4 comments

This is first post about Javascript snips which I feel interesting to learn or know. Most likely, the snips should be cross-browser compatible. But the term “cross-browser compatible” is awlays with certain condition. More accurate, they are the best effort to make them to be “cross-browser compatible”. Most of them can be easily found from Internet. They might be modified to ease my own understanding. I will not give any explanation on the script snip in any means, unless I have time to do so. Anyway, they should be not so difficult to be understood, simply with the help from Internet.

Just a note, I will put the snips into a function called underscore, which serves as the namespace for these snips collection.

Here we go, let’s start with calcuating the element’s position.

Script

underscore = {
    position: function (element) {
        var p = {x: element.offsetLeft || 0, y:element.offsetTop || 0};
        while (element = element.offsetParent) {
            p.x += element.offsetLeft;
            p.y += element.offsetTop;
        }
        return p;
    }
}

Usage

var divElement = document.getDocumentById("myid");
var p = underscore.position(divElement);
alert("position x:" + p.x + "; y:" + p.y);

Reference

Categories: javascript, Tech