How to get the scroll position of an element in JavaScript

When building a user interface in a browser, there may be a scrollable element, and you usually need to know the horizontal and vertical scrolling it currently has.

What should you do?

Once you have an element, you can check itsscrollLeftwithscrollTopcharacteristic.

This0, 0The position is always in the upper left corner, so any scrolling is relative to that position.

example:

const container = document.querySelector('. container')
container.scrollTop
container.scrollLeft

These attributes are read/write, so you can alsoputScroll position:

const container = document.querySelector('. container')
container.scrollTop = 1000
container.scrollLeft = 1000

Download mine for freeJavaScript beginner's manual


More browser tutorials: