Sami Al-Subhi
Sami Al-Subhi

Reputation: 4672

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

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/

Upvotes: 135

Views: 191162

Answers (16)

Ezra Siton
Ezra Siton

Reputation: 7781

**For anchor links (href="/#about") to anchor <div id="about"> read part 3.

1 (distance_from_top)

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 (window.scrollTo)

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>

3 (scrollTo & anchors)

scrollTo "conflict" with main anchor navbars

This trick is very buggy if, for example, you use this URL:

www.mysite/about#hello

to

<div id="hello">hello</div>

top is 0 or buggy (The HTML moves to hello section).

  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

Upvotes: 3

M.A Shahbazi
M.A Shahbazi

Reputation: 1081

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

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

Upvotes: 1

ulduz
ulduz

Reputation: 119

document.getElementById("id").offsetTop

Upvotes: 2

Julian Zepeda
Julian Zepeda

Reputation: 11

You only need this line

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

in which "el" is the element.

Upvotes: 1

Fanky
Fanky

Reputation: 1785

This oneliner seems to work nice

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

your fiddle updated

Upvotes: 11

Shawn Whinnery
Shawn Whinnery

Reputation: 3677

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.

Upvotes: 106

Uzma Ali
Uzma Ali

Reputation: 11

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

Upvotes: 1

Aras Ksgl
Aras Ksgl

Reputation: 21

scroll to element's top position;

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

Upvotes: 2

Ossaija Thankgod
Ossaija Thankgod

Reputation: 454

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/

Upvotes: 9

sachleen
sachleen

Reputation: 31141

Use offsetTop

document.getElementById("foo").offsetTop

Demo

Upvotes: 15

eeglbalazs
eeglbalazs

Reputation: 2136

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

Upvotes: 169

CodeMonk
CodeMonk

Reputation: 920

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

Upvotes: 2

Kelvin Jardin
Kelvin Jardin

Reputation: 101

var distanceTop = element.getBoundingClientRect().top;

For details vist a link:

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

Upvotes: 6

www139
www139

Reputation: 5237

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>

Upvotes: 16

T.Todua
T.Todua

Reputation: 56557

(SOURCE : Determine distance from the top of a div to top of window with javascript )

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

Upvotes: 1

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74272

Using jQuery's offset() method:

$(element).offset().top

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

Upvotes: -8

Related Questions