Last active
May 4, 2023 08:05
-
-
Save ilfey/d0fca81c6b713d21d106e4deaa5c912c to your computer and use it in GitHub Desktop.
scroll to element for react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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