Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grab the x, y position of html elements with javascript

I have in my html document several div elements with certain css class and want to get x, y position of those elements, thanks in advance.

like image 894
Nudier Mena Avatar asked Jun 01 '12 15:06

Nudier Mena


2 Answers

Use getBoundingClientRect: http://ejohn.org/blog/getboundingclientrect-is-awesome/

For example:

var div = document.getElementById("yourDiv");
var rect = div.getBoundingClientRect();
alert("Coordinates: " + rect.left + "px, " + rect.top + "px");

Remember that getBoundingClientRect gives the coordinates relative to the current viewport, which means that if you want to know the coordinates relative to the document.body, you have to add the horizontal and vertical scroll amounts (document.documentElement.scrollLeft or document.body.scrollLeft for Firefox, and .scrollTop of course).

like image 114
MaxArt Avatar answered Sep 28 '22 10:09

MaxArt


If I understand, you want to do this http://www.quirksmode.org/js/findpos.html

like image 35
jakubiszon Avatar answered Sep 28 '22 10:09

jakubiszon