User Tools

Site Tools


javascript:position:get_absolute_position_from_top_or_left_of_document_x_y

JavaScript - Position - Get absolute position from top or left of document (x, y)

Using offsetTop and offsetLeft

  • Only gives the distance between the element and it’s nearest “offsetParent” (which is the element that controls it’s position).
  • If you have an element with position: absolute and top: 100 and it has a child that flows naturally to 100px within it, the offsetTop of that element will be 100, not 200 as you might expect.

Better approach

There are really 2 ways to get the position of an element from the top/left of the body/document.

  1. window.pageXOffset + element.getBoundingClientRect().left (switch for pageYOffset and .top for vertical)
  2. Iterate through offset parents:
function getTop(element) {
  var y = 0;
  while (element != null && element != document.body) {
    y += element.offsetTop;
    element = element.offsetParent;
  }
  return y;
}
// substitute offsetLeft for horizontal
javascript/position/get_absolute_position_from_top_or_left_of_document_x_y.txt · Last modified: 2020/07/15 09:30 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki