javascript – How to determine the coordinates of an element

Question:

How to determine the coordinates of an element relative to the whole document and relative to the visible part of the window in javascript? After the onscroll event onscroll coordinates of the element relative to the visible part of the window should change. Thanks in advance.

Answer:

The coordinates are relative to the visible part of the document – .getBoundingClientRect() . This method also returns the width and height of the element.

document.querySelector('button').onclick = function() {
  var c = this.getBoundingClientRect()
  alert('top:' + c.top + ' left: ' + c.left +'');
}
button {
  margin: 500px 0 0;
}
span {
  display:block;
}
<div>
  <span>scroll down</span>
  <button>getBoundingClientRect()</button>
<div>

Coordinates relative to the beginning of the document – value .scrollTop / .scrollLeft + .getBoundingClientRect().top / .getBoundingClientRect().left

document.querySelector('button').onclick = function() {
  var c = this.getBoundingClientRect(),
      scrolltop = document.body.scrollTop + c.top,
      scrollleft = document.body.scrollLeft + c.left;
  alert('top:' + scrolltop + ' left: ' + scrollleft + '');
}
button {
  margin: 500px 0 0 500px;
}
span {
  display: block;
}
<div>
  <span>scroll down & left</span>
  <button>getBoundingClientRect() + scrollTop</button>
</div>

More details at learn.javascript.ru/coordinates

MDN: .scrollTop , .getBoundingClientRect ()

Scroll to Top