What is compute-scroll-into-view?
The compute-scroll-into-view npm package is a utility that calculates the scroll position necessary to make an element visible within its container. This is useful for smoothly scrolling items into view, especially in custom scrolling interfaces where the default browser behavior does not suffice.
Compute scroll position
This feature calculates the necessary scroll positions to bring an element into view within its container. The function returns an array of actions that can be applied to achieve the desired scroll effect. Each action specifies the element to scroll and the new top and left scroll positions.
import computeScrollIntoView from 'compute-scroll-into-view';
const element = document.getElementById('targetElement');
const actions = computeScrollIntoView(element, {
scrollMode: 'if-needed',
block: 'nearest',
inline: 'nearest'
});
actions.forEach(({ el, top, left }) => {
el.scrollTop = top;
el.scrollLeft = left;
});