This used to be a ponyfill for
Element.scrollIntoViewIfNeeded
. Since then the CSS working group have decided to implement its features in Element.scrollIntoView
as the option scrollMode: "if-needed"
. Thus this library got rewritten to implement that spec instead of the soon to be deprecated one.
Install
yarn add scroll-into-view-if-needed
Usage
import scrollIntoView from 'scroll-into-view-if-needed'
const scrollIntoView = require('scroll-into-view-if-needed')
const node = document.getElementById('hero')
scrollIntoView(node, {
scrollMode: 'if-needed',
block: 'nearest',
inline: 'nearest',
})
scrollIntoView(node, { block: 'center', inline: 'center' })
scrollIntoView(node, { behavior: 'smooth', scrollMode: 'if-needed' })
Ponyfill smooth scrolling
What does ponyfilling smooth scrolling mean, and why is it implemented in smooth-scroll-into-view-if-needed
instead?
The answer is bundlesize. If this package adds smooth scrolling to browsers that's missing it then the overall bundlesize increases regardless of wether you use this feature or not.
Put it this way:
import scrollIntoView from 'scroll-into-view-if-needed'
scrollIntoIntoView(node, { scrollMode: 'if-needed' })
scrollIntoIntoView(node, { behavior: 'smooth', scrollMode: 'if-needed' })
Because of this you need to choose a strategy that matches your priorities: load time, consistency or quality.
Load time
In many scenarios smooth scrolling can be used as a progressive enhancement. If the user is on a browser that don't implement smooth scrolling it'll simply scroll instantly and your bundlesize is only as large as it has to be.
import scrollIntoView from 'scroll-into-view-if-needed'
scrollIntoView(node, { behavior: 'smooth' })
Consistency
If a consistent smooth scrolling experience is a priority and you really don't want any surprises between different browsers and enviroments. In other words don't want to be affected by how a vendor might implement native smooth scrolling, then smooth-scroll-into-view-if-needed
is your best option. It ensures the same smooth scrolling experience for every browser.
import smoothScrollIntoView from 'smooth-scroll-into-view-if-needed'
smoothScrollIntoView(node, { behavior: 'smooth' })
Quality
If you want to use native smooth scrolling when it's available, and fallback to the smooth scrolling ponyfill:
import scrollIntoView from 'scroll-into-view-if-needed'
import smoothScrollIntoView from 'smooth-scroll-into-view-if-needed'
const scrollIntoViewSmoothly =
'scrollBehavior' in document.documentElement.style
? scrollIntoView
: smoothScrollIntoView
scrollIntoViewSmoothly(node, { behavior: 'smooth' })
API
scrollIntoView(target, [options])
New API introduced in v1.3.0
options
Type: Object
behavior
Type: 'auto' | 'smooth' | 'instant' | Function
Default: 'auto'
Introduced in v2.1.0
'auto'
The auto option unlocks a few interesting opportunities.
The browser will decide based on user preferences wether it should smooth scroll or not.
On top of that you can control/override scrolling behavior through the scroll-behavior
CSS property.
Some people get motion sick from animations. You can use CSS to turn off smooth scrolling in those cases to avoid making them dizzy:
html,
.scroll-container {
overflow: scroll;
}
html,
.scroll-container {
scroll-behavior: smooth;
}
@media (prefers-reduced-motion) {
html,
.scroll-container {
scroll-behavior: auto;
}
}
Quick note, in the CSS property the auto
keyword equals behavior: 'instant'
, not behavior: 'auto'
on scrollIntoView
. Yes, this is confusing.
'smooth'
Using behavior: 'smooth'
is the easiest way to smooth scroll an element as it does not require any CSS, just a browser that implements it. More information.
'instant'
This is useful for scenarios where it's certain that smooth scrolling would make an interaction feel sluggish. Like keyboard navigation and other user experiences where the end user expect things to move instantly.
Function
When given a function then this library will only calculate what should be scrolled and leave it up to you to perform the actual scrolling.
The callback is given an array over actions. Each action contain a reference to an element that should be scrolled, with its top and left scrolling coordinates.
What you return is passed through, allowing you to implement a Promise interface if you want to (check smooth-scroll-into-view-if-needed
to see an example of that).
import scrollIntoView from 'scroll-into-view-if-needed'
const node = document.getElementById('hero')
scrollIntoView(node, {
behavior: actions =>
actions.forEach(({ el, top, left }) => {
el.scrollTop = top
el.scrollLeft = left
const offsetTop = el.scrollTop - top
const offsetLeft = el.scrollLeft - left
}),
})
Check the demo to see an example with popmotion and a spring transition.
block
Type: 'start' | 'center' | 'end' | 'nearest'
Default: 'center'
Introduced in v2.1.0
Control the logical scroll position on the y-axis. The spec states that the block
direction is related to the writing-mode, but this is not implemented yet in this library.
This means that block: 'start'
aligns to the top edge and block: 'end'
to the bottom.
inline
Type: 'start' | 'center' | 'end' | 'nearest'
Default: 'nearest'
Introduced in v2.1.0
Like block
this is affected by the writing-mode. In left-to-right pages inline: 'start'
will align to the left edge. In right-to-left it should be flipped. This will be supported in a future release.
scrollMode
Type: 'always' | 'if-needed'
Default: 'always'
Introduced in v2.1.0
This is a proposed addition to the spec that you can track here: https://github.com/w3c/csswg-drafts/pull/1805
This library will be updated to reflect any changes to the spec and will provide a migration path.
To be backwards compatible with Element.scrollIntoViewIfNeeded
if something is not 100% visible it will count as "needs scrolling". If you need a different visibility ratio your best option would be to implement an Intersection Observer.
boundary
Type: Element | Function
Function
introduced in v2.1.0
, Element
introduced in v1.1.0
By default there is no boundary. All the parent elements of your target is checked until it reaches the viewport (document.documentElement
) when calculating layout and what to scroll.
You can use this option to do things like:
- Prevent the browser window from scrolling.
- Scroll things into view below the fold without scrolling to it.
- Scroll elements into view in a list, without scrolling container elements.
- Prematurely optimizing performance instead of code-splitting your app.
You can also pass a function to do more dynamic checks to override the scroll scoping:
scrollIntoView(target, {
boundary: parent => {
if (getComputedStyle(parent)['overflow'] === 'hidden') {
return false
}
return true
},
})
Breaking API changes from v1
Since v1 ponyfilled Element.scrollIntoViewIfNeeded, while v2 ponyfills Element.scrollIntoView, there are breaking changes from the differences in their APIs.
The biggest difference is that the new behavior follows the spec, so the "if-needed" behavior is not enabled by default:
v1
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
scrollIntoViewIfNeeded(target)
v2
import scrollIntoView from 'scroll-into-view-if-needed'
scrollIntoView(target, { block: 'nearest', scrollMode: 'if-needed' })
centerIfNeeded
The old Element.scrollIntoView
api only had two settings, align to top or bottom. Element.scrollIntoViewIfNeeded
had two more, align to the center or nearest edge.
The Element.scrollIntoView
spec now supports these two modes as block: 'center'
and block: 'nearest'
.
Breaking changes sucks, but on the plus side your code is now more portable and will make this library easier to delete from your codebase on the glorious day browser support is good enough.
v1
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
scrollIntoViewIfNeeded(target, { centerIfNeeded: true })
scrollIntoViewIfNeeded(target, { centerIfNeeded: false })
scrollIntoViewIfNeeded(target, true)
scrollIntoViewIfNeeded(target, false)
v2
import scrollIntoView from 'scroll-into-view-if-needed'
scrollIntoView(target, { block: 'center' })
scrollIntoView(target, { block: 'nearest' })
duration
More information.
v1
import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
scrollIntoViewIfNeeded(target, { duration: 300 })
v2
import scrollIntoView from 'scroll-into-view-if-needed'
import scrollIntoView from 'smooth-scroll-into-view-if-needed'
scrollIntoView(target, { behavior: 'smooth' })
easing
This feature is removed, but you can achieve the same thing by implementing behavior: Function
.
handleScroll
This is replaced with behavior: Function
with one key difference. Instead of firing once per element that should be scrolled, the new API only fire once and instead give you an array so you can much easier batch and scroll multiple elements at the same time. Or sync scrolling with another element if that's the kind of stuff you're into, I don't judge.
-import scrollIntoViewIfNeeded from 'scroll-into-view-if-needed'
+import scrollIntoView from 'scroll-into-view-if-needed'
-scrollIntoViewIfNeeded(node, {handleScroll: (el, {scrollTop, scrollLeft}) => {
- el.scrollTop = scrollTop
- el.scrollLeft = scrollLeft
-}})
+scrollIntoView(node, {behavior: actions.forEach(({el, top, left}) => {
+ el.scrollTop = top
+ el.scrollLeft = left
+})})
offset
This was always a buggy feature and warned against using in v1 as it might get dropped.
It's much safer to use CSS wrapper elements for this kind of thing.
scrollIntoViewIfNeeded(target, [centerIfNeeded], [animateOptions], [finalElement], [offsetOptions])
This API signature were warned to be dropped in v2.0.0
, and it was.
Related packages
Who's using this
- zeit.co/docs – Documentation of ZEIT Now and other services.
- Selenium IDE – An integrated development environment for Selenium scripts.
- Box UI Elements – Box UI Elements are pre-built UI components that allow developers to add elements of the main Box web application into their own applications.
- react-responsive-ui – Responsive React UI components.
- Mineral UI –
A design system and React component library for the web that lets you quickly build high-quality, accessible apps.
- Covalent – Teradata UI Platform built on Angular Material.
- docs.expo.io – Documentation for Expo, its SDK, client and services.
- Add yourself to the list 😉