A CSS selector or an element to scroll into view.
Whether to use smooth scrolling. Defaults to true.
Optional
onScrollComplete: (Optional callback invoked after scroll attempt with info about the element, any error, and how long the scroll attempt took (in milliseconds).
// ES Module
import { scrollToElementAfterRender } from '@bnidev/js-utils'
// CommonJS
const { scrollToElementAfterRender } = require('@bnidev/js-utils')
// Scroll to an element by CSS selector
scrollToElementAfterRender('#myElement')
// Scroll to an element by CSS selector instantly (no smooth scrolling)
scrollToElementAfterRender('#myElement', false)
// Scroll to a DOM element reference
const el = document.getElementById('myElement')
if (el) {
scrollToElementAfterRender(el)
}
// Scroll with a completion callback
scrollToElementAfterRender('#myElement', true, ({ element, error, durationMs }) => {
if (error) console.error('Scroll failed:', error)
else console.log('Scrolled element:', element, 'in', durationMs, 'ms')
})
Scrolls the element with the specified CSS selector or element reference into view after the next render frame.
Uses
requestAnimationFrame
to ensure the scroll occurs after rendering.