Categories
css dom html javascript position

Retrieve the position (X,Y) of an HTML element

2096

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

6

  • 8

    i had been using these 7 lines of code which works in all browsers with discrepancies in ie5,6,7(i did not remember having any proboem… may be the doc type) … quirksmode.org/js/findpos.html and i had been using it a lot for so many years. may be sombody can point the flaws if any.

    Apr 2, 2015 at 15:27


  • 124

    @AnthonyWJones, I suppose you needed the pedantic pleasure, but it is obvious, as it always is when unspecified, that the OP refers to the most general case, or refers to the window coordinates of the browser.

    – Motes

    May 26, 2015 at 20:29

  • 17

    @Mote, No, it’s not that obvious. Leave inference, subjectivity and false axioms aside. It can be relative to viewport or top of the page (aka document.documentElement).

    Oct 22, 2017 at 2:27

  • 21

    Defaulting to the most general is not inference, it is the logical progression, so that would be relative to the window, or “top of page” might be the term as you put it. In Game Theory, it is codified as a concept called a Schelling point. Be sure to specify when you don’t mean the most general case.

    – Motes

    Oct 22, 2017 at 18:45

  • 9

    The point is, the obvious for some is not obvious for others. Even if in theory we know which is the case, due to empirical knowledge, clarity hurts no one here, specially for those who just started programming.

    Jan 22, 2019 at 20:22

385

This function returns an element’s position relative to the whole document (page):

function getOffset(el) {
  const rect = el.getBoundingClientRect();
  return {
    left: rect.left + window.scrollX,
    top: rect.top + window.scrollY
  };
}

Using this we can get the X position:

getOffset(element).left

… or the Y position:

getOffset(element).top

1

360

The libraries go to some lengths to get accurate offsets for an element.
here’s a simple function that does the job in every circumstances that I’ve tried.

function getOffset( 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 };
}
var x = getOffset( document.getElementById('yourElId') ).left; 

2

  • 16

    change: el = el.parentNode to: el = el.offsetParent; and it seems to work for nested iframes now… I’m thinking that’s what you intended?

    – Adam

    Jul 29, 2009 at 20:19

  • Tested this out, it works amazing even with a zoom level present!

    – Jordash

    Jun 1 at 16:28