728x90
I want to know how to get the X and Y position of HTML elements such as img and div in JavaScript.

20 Answers 20

The correct approach is to use element.getBoundingClientRect():

var rect = element.getBoundingClientRect();
console.log(rect.top, rect.right, rect.bottom, rect.left);

Internet Explorer has supported this since as long as you are likely to care about and it was finally standardized in CSSOM Views. All other browsers adopted it a long time ago.

Some browsers also return height and width properties, though this is non-standard. If you're worried about older browser compatibility, check this answer's revisions for an optimised degrading implementation.

The values returned by element.getBoundingClientRect() are relative to the viewport. If you need it relative to another element, simply subtract one rectangle from the other:

var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

alert('Element is ' + offset + ' vertical pixels from <body>');
728x90

'WEB' 카테고리의 다른 글

tomcat console 한글 깨짐  (0) 2020.01.19
네이버 스마트에디터(smarteditor2) 파일 업로드 0바이트 오류  (0) 2019.09.30
html5 한글 깨짐 문제  (0) 2017.05.13
드래그 앤 드랍 예제  (0) 2017.05.13
STRUTS IOC  (0) 2014.11.28

+ Recent posts