You can scroll to an element with scrollIntoView. It takes in an object with three options:
behavior: smooth or auto
block: Position of the element you want to scroll to (vertically)
inline: Position of the element you want to scroll to (horizontally)
element.scrollIntoView(options)
block can take in one of the four values:
start (default)
end
center
nearest
start scrolls until the top of the target element reaches the top of the scrollable element. (start is a bit wonky. It forces the outer scrollable element to scroll as well).
end scrolls until the end of the target element reaches the bottom of the scrollable element.
center scrolls until the target element is in the center of the scrollable element.
nearest scrolls to start or end, depending on which is nearer.
inline takes in the same four values. Substitute left with top, and right with bottom
start: Scroll to the left of the element
end: Scroll to the right of the element
center: Position the element in the center
nearest (default): Scroll to the left or right of the element, depending on which is nearest
Caution about Scroll
The scroll event fires really quickly, as you can see from the GIF below.
Don’t run expensive operations (like changing the DOM with every scroll position) with the scroll event listener. You’ll create jank.