DOM scrollTop/scrollLeft cheatsheet
This is nothing new, just a note on how scrollTop
, scrollHeight
, clientHeight
and related properties work.
Quick illustration
== See interactive demo ==
- scrollTop [RW] is the amount of pixels that the content of an element is scrolled upward, i.e. the amount of pixels that left the element's visible content area
- clientHeight [R] is the "inner" height of our element. It includes padding but excludes the horizontal scrollbar height (if present), border and margin
- scrollHeight [R] equals to the total height of element's inner content (includes padding) OR clientHeight if content is too short
Notes
- Scroll range is always limited! This one's important to realize as you might assume that there is an infinite canvas inside each element that you can scroll arbitrarily regardles of the actual content boundaries.
- It can't be negative [1]
- Maximum value is determined by the content.
- We can artificially "extend" scroll boundaries by placing a dummy element at a distance before or after the "payload" content
- Attempting to set a value for
scrollLeft
/scrollTop
that is outside of its range will set it to the closest boundary (0 or maximum) - When the element is scrolled to the end, the following holds true:
(vertical) scrollTop == scrollHeight - clientHeight
(horizontal) scrollLeft == scrollWidth - clientWidth
[1] - this is not true for RTL text flow environments (e.g. Arabic languages)
References
Some known quirks in browser implementations:
Written by Dmitry Pashkevich
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ui
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#