What is scroll-into-view-if-needed?
The scroll-into-view-if-needed npm package is a smooth scroll polyfill for the 'scrollIntoViewIfNeeded' DOM method, which allows elements to be scrolled into the viewport if they are not already visible. It provides a way to scroll an element into view, aligning it according to the specified options only if it is not already in view.
What are scroll-into-view-if-needed's main functionalities?
Basic scrolling into view if needed
This is the simplest use case where you can call the method on an element to ensure it is visible in the viewport.
element.scrollIntoViewIfNeeded();
Custom options for scrolling
This allows you to define custom options for the scrolling behavior, such as the alignment of the scrolled-to element within the viewport.
scrollIntoViewIfNeeded(node, {block: 'nearest', inline: 'nearest'});
Polyfill for unsupported browsers
The package can be used as a polyfill to provide the functionality in browsers that do not support 'scrollIntoViewIfNeeded' natively.
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed';
scrollIntoViewIfNeeded(node);
Other packages similar to scroll-into-view-if-needed
smoothscroll-polyfill
This package is a polyfill for the smooth scroll behavior in the scrollTo, scrollBy, and scrollIntoView methods. It is similar to scroll-into-view-if-needed but focuses on polyfilling the smooth scroll behavior across all scrolling methods.
scroll-into-view
Similar to scroll-into-view-if-needed, this package provides a function to scroll an element into view. However, it does not specifically check if the element is already in view and always performs the scroll action.
zenscroll
Zenscroll is a vanilla JavaScript library that enables smooth animated scrolling to elements on the page. While it provides similar smooth scrolling functionality, it does not have the conditional 'if-needed' aspect of scroll-into-view-if-needed.
scroll-into-view-if-needed
This is a ponyfill with the added ability of animating the scroll itself.
Kudos to @hsablonniere for sharing the original polyfill and @jocki84 for improving it!
Install
npm install scroll-into-view-if-needed
API
scrollIntoViewIfNeeded(node:Element, centerIfNeeded:boolean, options:object)
Returns a function that can be used to cancel a scroll animation.
Inspired by scroll-iv.
Options
centerIfNeeded
This defaults to true to match the behavior of the WebKit/Blink implementation.
Set it to false to actually only scroll the parent when needed and not further than absolutely necessary.
duration
The duration of the animation in milliseconds, defaults to 0 for no animation.
easing
default is ease. Possible values: ease|easeIn|easeOut|easeInOut|linear
Examples
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
const activeNode = document.querySelector('li.active')
scrollIntoViewIfNeeded(activeNode, false)
scrollIntoViewIfNeeded(activeNode, false, {
duration: 150
})