Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scrollTop vs getBoundingClientRect().top

I thought $(window).scrollTop would tell me by how much I had scrolled, but...

If I scroll a bit, I'll get:

$(window).scrollTop(): 0
$('#react-root')[0].scrollTop: 0
$('#react-root')[0].getBoundingClientRect().top: -450 // that seems to be correct

#react-root being directly attached to the body, and containing everything. Is it how things are supposed to happen?

==== Edit ===

Ok I happened to have an unusual overflow settings:

html {
  overflow: hidden;
  height: 100%;
}

body {
  height: 100%;
  overflow: scroll;
}

That I did to avoid over scrolling (https://stackoverflow.com/a/17899813/2054629) and forgot about it.

Here is a jsfiddle that reproduces the issue https://jsfiddle.net/7ugf4jm5/7/ where none of the elements has a positive scrolltop, while scrolling do happen

==== Goal ====

In the setting described by the jsfiddle, I'm interested to get the scroll offset (it seems that getBoundingClientRect returns it) and be able to reset the scroll position to the top.

like image 565
Guig Avatar asked Jul 26 '26 06:07

Guig


1 Answers

I made this fiddle to show you an example: https://jsfiddle.net/7ugf4jm5/

Inner Element in Fiddle

When scrolling the inner element:

console.log("Inner ID: " + $('#inner')[0].scrollTop);
console.log("Window: " + $(window).scrollTop());
console.log("Inner ID Bound: " + $('#inner')[0].getBoundingClientRect().top);

Will output:

Inner ID: 555.5555702727522
Window: 0
Inner ID Bound: 7.986111640930176 --> Only because there is a slight padding at the top of the element

Outer Element In Fiddle

console.log("React ID: " + $('#react-root')[0].scrollTop);
console.log("Window: " + $(window).scrollTop());
console.log("React ID Bound: " + $('#react-root')[0].getBoundingClientRect().top);

Outputs:

React ID: 0
Window: 666.6666843273026
React ID Bound: -658.6806030273438

$(window).scrollTop() will work when the browser is being scrolled. If you have your react-root set to overflow scroll, it will stay positioned at the top of the window so the window is not what is getting scrolled. You can see this example with the element outlined in red in my fiddle.

However, if you scroll the window, both the react-root and window scroll tops are calculated. They differ slightly but that can be due to the time at which each is called in the browser being slightly different (one is essentially called after the other..just at a very tiny difference in time).

The scrollTop and getBoundingClientRect() are sign inverses of eachother in this case.

like image 192
A.Sharma Avatar answered Jul 27 '26 18:07

A.Sharma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!