Javascript: Calculate Element Position
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);
Hello š
Just a simple point of view about this function:
if an element hasn’t offsetLeft property, used browser is really old or not compatible with function itself.
And if offsetLeft is not present, offsetParent isn’t present too.
I didn’t add “|| 0” on my bytefx function because if offsetLeft or offsetRight are 0, this function need to do one or two unuseful operations while if offsetLeft and then Right is null, you can skip every kind of function that’s based on this one (if p.x !== null){//do stuff}
In your example, this is not possible because returned number will be atleast 0 and never null … then in my opinion this version:
var position = {x:element.offsetLeft, y:element.offsetTop};
while(element = element.offsetParent){
position.x += element.offsetLeft;
position.y += element.offsetTop;
};
return position;
is better and even light for a crossbrowser lib or code š
uhm … I ment undefined … not null, sorry š
Somehow i missed the point. Probably lost in translation š Anyway … nice blog to visit.
cheers, Contestable
.
Hey,
Please correct this error in your code:
“getDocumentById” should be “getElementById”