KaisarCode

Scripting 4 freeDOM



JS Get Position

by KaisarCode

function getPos(elem){
	//get the position [left,top] relative to whole document
	var tmp=elem;
	var left=tmp.offsetLeft;
	var top=tmp.offsetTop;
	while (tmp=tmp.offsetParent) left += tmp.offsetLeft;
	tmp=elem;
	while(tmp=tmp.offsetParent) top+=tmp.offsetTop;
	return [left,top];
}

Well, keeping up with the small functions used in the JavaScript Rotate, now is the turn for the getPos() one.

The promise is simple, it returns the position on screen of the designed element, relative to the bounds of the viewport.

This function is simple, yet a little bit tricky, since we all are used to do this type of position checking using frameworks, but not all knows how this can be done.

The problem comes when we think that checking the left and top property is enough, and that's not at all, because if we're dealing with an element placed inside a relative positioned parent, this properties will throw back the position in relationship with that parent, and not the document border itself.

Let's check this examples:

Without getPos():

This should be done checking the offsetLeft and offsetTop properties, as many tutorials over the Internet will tell you, but let's see which are the values that this implementation returns:

Click Me
var posbox1=document.getElementById("pos-box-1");
posbox1.onclick=function(){
	var posleft=this.offsetLeft;
	var postop=this.offsetTop;
	alert("Left: "+posleft+"px - Top:"+postop+"px");
}

5px? 2px? No way, our element is pretty far away from the bounds! Now, let's see what happens applying the getPos function

Using getPos():

Click Me
var posbox2=document.getElementById("pos-box-2");
posbox2.onclick=function(){
	var pos=getPos(this);
	var posleft=pos[0];
	var postop=pos[1];
	alert("Left: "+posleft+"px - Top:"+postop+"px");
}

Now it's different, it is showing the real position on screen.

How?

This function also uses offsetLeft and offsetTop, but the trick is on the while block that you can see here:

while(tmp=tmp.offsetParent) top+=tmp.offsetTop;

Here, we detect if the current element has, actually a parent, and we add its top or left position to the variable that we're gonna return.

Also, we overwrite the variable that keeps the main target element, with its parent, looping until there are no more parents (and we get to the root element).

At the end, we return this addition as the true amount of pixels to the page's boundaries. This is the way to get the real position on screen.


I hope this was helpful, and see you soon.