How to get the distance from the top for an element?

Viewed 142646

I want to know how to use JavaScript to get the distance of an element from the top of the page not the parent element.
enter image description here

http://jsfiddle.net/yZGSt/1/

16 Answers
var elDistanceToTop = window.pageYOffset + el.getBoundingClientRect().top

In my experience document.body.scrollTop doesn't always return the current scroll position (for example if the scrolling actually happens on a different element).

offsetTop doesn’t get the distance to the top of the page, but rather to the top of the closest parent element that has a specified position.

You can use a simple technique that adds up the offsetTop of all the parent element of the element you are interested in to get the distance.

// Our element
var elem = document.querySelector('#some-element');

// Set our distance placeholder
var distance = 0;

// Loop up the dom
do {
    // Increase our distance counter
    distance += elem.offsetTop;

    // Set the element to it's parent
    elem = elem.offsetParent;

} while (elem);
distance = distance < 0 ? 0 : distance;

Original code from https://gomakethings.com/how-to-get-an-elements-distance-from-the-top-of-the-page-with-vanilla-javascript/

This oneliner seems to work nice

document.getElementById("el").getBoundingClientRect().top +  window.scrollY

your fiddle updated

scroll to element's top position;

var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;

warning warning warning warning warning warning

"Classic case" - URL "/#about-us" and div with an id of "about-us". In this case, the top position set by default anchor click behavior (So the top is 0 for about-us div). You must prevent default (Or you'll go crazy for why it doesn't work -or- any other code you find out there). More details below under "warning".

1

Less than 30 seconds solution (Two lines of code "hello world"):

get your element:

var element = document.getElementById("hello");

Get getBoundingClientRect ();

The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

var rect = element.getBoundingClientRect();

Return object:

enter image description here

Dot notation top

var distance_from_top = rect.top; /* 1007.9971313476562 */

Thats it.

2

StackOverflow nightmare 2 - set scroll position to this value

Again "hello world" (8,000 answers out there - 7,999 not working or to complex).

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo

  window.scrollTo({
    top: element.getBoundingClientRect().top,
    behavior: 'smooth'
  });

Add offset value to top if you want (For sticky navbars).

"Hello World" code snippet (Get distance from top viewport + click to scrollTo)

var element = document.getElementById("hello");
var rect = element.getBoundingClientRect();
var distance_from_top = rect.top; /* 50px */
console.log(distance_from_top);

function scrollTovView(){
  window.scrollTo({
    top: distance_from_top,
    behavior: 'smooth'
  });
}
div{
  text-align:center;
  border: 1px solid lightgray;
}
<button onclick="scrollTovView()">scrollTo to red DIV</button>
<div style="height: 50px;">50px height</div>
<div id="hello" style="width: 500px; height: 500px; background: red;"></div>

warning

scrollTo "conflict" with main anchor navbars

This trick is very buggy if, for example, you use this URL (ID to anchor URL)(Top is 0 or "get crazy" hh).

www.mysite/about#hello
  window.scrollTo({
    top: element.getBoundingClientRect().top,
    behavior: 'smooth'
  });

For this code to work you should add:

    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

Basic example her: https://www.w3schools.com/howto/howto_css_smooth_scroll.asp

document.getElementById("id").offsetTop

This function returns distance from top of the page, even if your window is scrolled. It can be used in event listeners.

const getElementYOffset = (element) => {
  const scrollOnWindow =
    window.pageYOffset !== undefined
      ? window.pageYOffset
      : (document.documentElement || document.body.parentNode || document.body)
          .scrollTop;
  const rect = element.getBoundingClientRect();
  let distanceFromTopOfPage = rect.top;
  if (scrollOnWindow !== 0) {
    distanceFromTopOfPage = rect.top + scrollOnWindow;
  }

  return distanceFromTopOfPage;
};

You only need this line

document.getElementById("el").getBoundingClientRect().top

in which "el" is the element.

Since window.pageYOffset is a legacy alias of window.scrollY, eeglbalazs answer can be improved to:

const elDistanceToTop = window.scrollY + el.getBoundingClientRect().top;
Related