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

Javascript

Javascript Problem Overview


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/

Javascript Solutions


Solution 1 - Javascript

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).

Solution 2 - Javascript

offsetTop only looks at the element's parent. Just loop through parent nodes until you run out of parents and add up their offsets.

function getPosition(element) {
    var xPosition = 0;
    var yPosition = 0;

    while(element) {
        xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
        yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
        element = element.offsetParent;
    }

    return { x: xPosition, y: yPosition };
}

UPDATE: This answer has some problems, values will have tiny differences compare to what it should be and will not work correctly in some cases.

Check @eeglbalazs's answer, which is accurate.

Solution 3 - Javascript

Use offsetTop

document.getElementById("foo").offsetTop

Demo

Solution 4 - Javascript

Here is some interesting code for you :)

window.addEventListener('load', function() {
  //get the element
  var elem = document.getElementById('test');
  //get the distance scrolled on body (by default can be changed)
  var distanceScrolled = document.body.scrollTop;
  //create viewport offset object
  var elemRect = elem.getBoundingClientRect();
  //get the offset from the element to the viewport
  var elemViewportOffset = elemRect.top;
  //add them together
  var totalOffset = distanceScrolled + elemViewportOffset;
  //log it, (look at the top of this example snippet)
  document.getElementById('log').innerHTML = totalOffset;
});

#test {
  width: 100px;
  height: 100px;
  background: red;
  margin-top: 100vh;
}
#log {
  position: fixed;
  top: 0;
  left: 0;
  display: table;
  background: #333;
  color: #fff;
}
html,
body {
  height: 2000px;
  height: 200vh;
}

<div id="log"></div>
<div id="test"></div>

Solution 5 - Javascript

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/

Solution 6 - Javascript

var distanceTop = element.getBoundingClientRect().top;

For details vist a link:

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

Solution 7 - Javascript

This oneliner seems to work nice

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

your fiddle updated

Solution 8 - Javascript

Although it is quite an old discussion, but this works pretty well on chrome / firefox / safari browsers:

window.addEventListener('scroll', function() {
   var someDiv = document.getElementById('someDiv');
   var distanceToTop = someDiv.getBoundingClientRect().top;
});

Check it out on JSFiddle

Solution 9 - Javascript

scroll to element's top position;

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

Solution 10 - Javascript

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

Solution 11 - Javascript

document.getElementById("id").offsetTop

Solution 12 - Javascript

(SOURCE : https://stackoverflow.com/questions/9880472/determine-distance-from-the-top-of-a-div-to-top-of-window-with-javascript/32737911#32737911 )

<script type="text/javascript">
var myyElement = document.getElementById("myyy_bar");  //your element
var EnableConsoleLOGS = true;                          //to check the results in Browser's Inspector(Console), whenever you are scrolling



// ==============================================
window.addEventListener('scroll', function (evt) {
    var Positionsss =  GetTopLeft ();  
    if (EnableConsoleLOGS) { console.log(Positionsss); }
});
function GetOffset (object, offset) {
    if (!object) return;
    offset.x += object.offsetLeft;       offset.y += object.offsetTop;
    GetOffset (object.offsetParent, offset);
}
function GetScrolled (object, scrolled) {
    if (!object) return;
    scrolled.x += object.scrollLeft;    scrolled.y += object.scrollTop;
    if (object.tagName.toLowerCase () != "html") {          GetScrolled (object.parentNode, scrolled);        }
}

function GetTopLeft () {
    var offset = {x : 0, y : 0};        GetOffset (myyElement, offset);
    var scrolled = {x : 0, y : 0};      GetScrolled (myyElement.parentNode, scrolled);
    var posX = offset.x - scrolled.x;   var posY = offset.y - scrolled.y;
    return {lefttt: posX , toppp: posY };
}
// ==============================================
</script>

Solution 13 - Javascript

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;
};

Solution 14 - Javascript

You only need this line

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

in which "el" is the element.

Solution 15 - Javascript

Using jQuery's offset() method:

$(element).offset().top

Example: http://jsfiddle.net/yZGSt/3/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSami Al-SubhiView Question on Stackoverflow
Solution 1 - JavascripteeglbalazsView Answer on Stackoverflow
Solution 2 - JavascriptShawn WhinneryView Answer on Stackoverflow
Solution 3 - JavascriptsachleenView Answer on Stackoverflow
Solution 4 - Javascriptwww139View Answer on Stackoverflow
Solution 5 - JavascriptOssaija ThankgodView Answer on Stackoverflow
Solution 6 - JavascriptKelvin JardinView Answer on Stackoverflow
Solution 7 - JavascriptFankyView Answer on Stackoverflow
Solution 8 - JavascriptCodeMonkView Answer on Stackoverflow
Solution 9 - JavascriptAras KsglView Answer on Stackoverflow
Solution 10 - JavascriptEzra SitonView Answer on Stackoverflow
Solution 11 - JavascriptulduzView Answer on Stackoverflow
Solution 12 - JavascriptT.ToduaView Answer on Stackoverflow
Solution 13 - JavascriptUzma AliView Answer on Stackoverflow
Solution 14 - JavascriptJulian ZepedaView Answer on Stackoverflow
Solution 15 - JavascriptAlan Haggai AlaviView Answer on Stackoverflow