Skip to content

Instantly share code, notes, and snippets.

@ilfey
Last active May 4, 2023 08:05
Show Gist options
  • Select an option

  • Save ilfey/d0fca81c6b713d21d106e4deaa5c912c to your computer and use it in GitHub Desktop.

Select an option

Save ilfey/d0fca81c6b713d21d106e4deaa5c912c to your computer and use it in GitHub Desktop.
scroll to element for react
function scrollToElement(el: HTMLElement, onScrollEnd = () => { }) {
const { top } = el.getBoundingClientRect()
var step = 75
var iterationsCount = Math.abs(Math.floor(top / step))
if (top < 0) {
step = -step
iterationsCount += 1
}
function inner(iterations: number) {
if (iterations !== 0) {
window.scrollBy(0, step)
setTimeout(inner, 5, iterations - 1)
}
}
setTimeout(inner, 5, iterationsCount)
onScrollEnd()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment