Reputation: 2143
I am working with the getBoundingClientRect function and trying to understand its top
behavior. What does the negative top mean?
In the example below, when you scroll down the values of top
become negative. Could someone please explain, how do I interpret the negative top values from getBoundingClientRect
?
document.addEventListener("scroll", () => {
let element = document.getElementById("test");
let rect = element.getBoundingClientRect();
console.log(rect.bottom, "bottom....top", rect.top, "...window.innerHeight", window.innerHeight)
});
body {
height: 100px
}
p {
width: 100%;
height: 500px;
margin-top: 1000px;
}
<p id="test">
Hello there
</p>
Upvotes: 0
Views: 5906
Reputation: 911
What the Element.getBoundingClientRect()
method returns is the position of an element relative to the viewport.
See the viewport as a coordinate system with x and y axles where the origin (0,0) is at the top left of the screen. Positive x increases toward the right and positive y increases toward the bottom (see illustration).
Let's take your code sample into the mix.
The body of the page has a height of 100px and the <p>
has a margin-top of 1000px, so the initial distance from the top of the page (y) is +1000px. When you scroll down, the element moves up, thus the "y" value decreases until the point that the top of the element reaches the top of the viewport. When this happens y becomes 0 and if you scroll any further down it becomes negative.
Upvotes: 2
Reputation: 33439
Your link you posted explains it all:
From MDN | Element.getBoundingClientRect (emphasis mine)
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.
The viewport is the window/iframe.
So the negative value means that the top of the element is scrolled out of view at the top of the viewport. When you scroll down, the top value becomes smaller as the distance to the viewport's top gets smaller. The moment the top border of #test
hits the top border of the view port, the top value logged becomes zero. When you scroll further, the value will become negative.
I've illustrated this with your example where I added a border to the #test
paragraph
document.addEventListener("scroll", () => {
let element = document.getElementById("test");
let rect = element.getBoundingClientRect();
console.log("top", rect.top)
});
body {
height: 100px
}
#test {
width: 100%;
height: 50vh;
margin-top: 50vh;
margin-bottom: 100vh;
border: 1px solid black;
}
<p id="test">
Hello there
</p>
Upvotes: 4
Reputation: 261
The Element.getBoundingClientRect() method returns the size of an element and its position relative to the viewport.
From Doc
Negative values means it's top is before the viewport top, so it basically means that the element location starts from before the VP starts
Upvotes: 1