Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the jQuery scrollTop value mean?

I'm working on some jquery code using the scrollTop method to implement an infinite scroll (please, don't suggest jQuery plugins, I know they exist) and I don't quite understand what this value means.

Given this fiddle: https://jsfiddle.net/ve8s5fdx/

<div id="outter">
  <div class="inner"></div>
  <div class="inner"></div>
</div>
<div id="scroll"></div>
#outter {
  height: 100px;
  width: 100%;
  overflow-y:auto;
}

.inner {
  height: 150px;
  width: 50%;
  border: dashed black 2px;
  background-color: grey;
}

It makes sense that the value is 0 when the scrollbar is at the very top of the element, but why "208" when it's at the bottom ? The #outter div is 100px high, its content a bit more than 300px.

like image 411
Valentin Coudert Avatar asked Oct 29 '22 19:10

Valentin Coudert


2 Answers

What @Rory McCrossan said. If you scrolled down 100px, the .scrollTop will display 100. The scrollTop will measure the space between the window and the element. So it doesn't matter how high your element is, it will always be the space above it that counts.

Since your .inner is missing the css-rule box-sizing: border-box; the border will be added outside the div, and it's 2px wide. Which in your case means that every .inner element is 154px high. You have 2 of those, so the content of .outer is 308px.

Your .outer-element is 100px high so 100px will always be visible. So when your window is scrolled to the very bottom, the scrollTop displays 308px - 100px = 208px.

If you change your .outer to the height of 50px, the scrollTop will display 258px when scrolled to the bottom.

like image 186
Jonathan Nielsen Avatar answered Nov 12 '22 20:11

Jonathan Nielsen


$.scrollTop:

The vertical scroll position is the same as the number of pixels that are hidden from view above the scrollable area. If the scroll bar is at the very top, or if the element is not scrollable, this number will be 0.

Inspecting your fiddle, you can see that your two .inners have a combined height of 308 px. Your outer (scrolling) div is 100 px tall.

So your .scrollTop(), the number of pixels that are hidden from view above the scrollable area is total inner height - visible height, or 208 px.

like image 21
msanford Avatar answered Nov 12 '22 21:11

msanford