This used to be a painful thing to find on the page. Well it wasn't but almost everyone suggested you use a hacky way to find the correct position of an element. The method was so popular that it wasn't even considered a hack. Here it is.
// the old way
function getPosition( el ) {
var x = 0;
var y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
x += el.offsetLeft - el.scrollLeft;
y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: y, left: x };
}
This works. What we are doing is grab an element, check its offset relative to its parent and save that value. We then grab the parent and do the same and increment the value until we rich the top element of the page.
We end up with the top
and left
coordinates of the element relative to the page. There is a better alternative however that should give us the same data in a more efficient matter.
Element.getBoundingClientRect()
This method gives us not only the same data but also the right
, bottom
, width
and height
.
element.getBoundingClientRect();
> ClientRect {}
bottom: 410
height: 50
left: 597
right: 762
top: 360
width: 165
One thing I always worry about when I use a new method in JavaScript is the compatibility with other browsers. Luckily, this method was available since Internet Explorer 4 and is available on all major browsers.
Note that this method gives you the position of an element relative to the window, not the page.
The time to ditch our earlier hack is long gone, but it is not too late to update your code to use this method instead.
Sign up for the Newsletter.
Comments(4)
Sourav Basak :
Good and very useful article for developing and managing web appication in a technicalways. This information can help the developers to modify any tricks without any hesitation. Also for building a short type of plugin this can also help to rebuild the construction of a page. Thanks a lot.
-- Regards, Sourav Basak [Blogger, Entrepreneur, Thinker]
Sandro Alvares :
Nice, but not same jquery .position() .. its real
I not found javascript original.
great different =(
thanks
Ibrahim :
Yes @Sandro. It is different then jQuery.
Derrick :
Nice, but getBoundingClientRect cause the reflow too, that's painful
Let's hear your thoughts