kxlb5a
Last Updated: February 25, 2016
·
981
· dpashkevich
D42a7264714dee5006b9c99d2567a320

DOM scrollTop/scrollLeft cheatsheet

This is nothing new, just a note on how scrollTop, scrollHeight, clientHeight and related properties work.

Quick illustration

Relationship between scrollTop, clientHeight and scrollHeight

== 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: