Reputation: 4672
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.
Upvotes: 135
Views: 191162
Reputation: 7781
**For anchor links (href="/#about"
) to anchor <div id="about">
read part 3.
Less than 30 seconds solution (Two lines of code "hello world"):
var element = document.getElementById("hello");
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:
top
var distance_from_top = rect.top; /* 1007.9971313476562 */
Thats it.
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).
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>
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
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
Reputation: 11
You only need this line
document.getElementById("el").getBoundingClientRect().top
in which "el" is the element.
Upvotes: 1
Reputation: 1785
This oneliner seems to work nice
document.getElementById("el").getBoundingClientRect().top + window.scrollY
Upvotes: 11
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
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
Reputation: 21
scroll to element's top position;
var rect = element.getBoundingClientRect();
var offsetTop = window.pageYOffset + rect.top - rect.height;
Upvotes: 2
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
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
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
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
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
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
Reputation: 74272
Using jQuery's offset()
method:
$(element).offset().top
Example: http://jsfiddle.net/yZGSt/3/
Upvotes: -8