Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

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

1 Answer

0 votes
by (40.7k points)

Try using the element.getBoundingClientRect() like this:

var rect = element.getBoundingClientRect();

console.log(rect.top, rect.right, rect.bottom, rect.left);

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 optimized degrading implementation.

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.

The values will be returned by element.getBoundingClientRect() are relative to the viewport. 

But, if you need it relative to another element, simply subtract one rectangle from the other like this:

var bodyRect = document.body.getBoundingClientRect(),

    elemRect = element.getBoundingClientRect(),

    offset   = elemRect.top - bodyRect.top;

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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...