What's the best way to implement js scroll to element smoothly? or How can I use js scroll to element

14 Replies, 658 Views

Dude, I feel you. The default js scroll to element is janky af in some browsers.

Try this vanilla approach:

```js
function smoothScrollTo(target) {
const start = window.scrollY;
const distance = target.getBoundingClientRect().top;
const duration = 1000;
let startTime = null;

function animation(currentTime) {
if (!startTime) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const ease = Math.min(timeElapsed / duration, 1);
window.scrollTo(0, start + distance * ease);
if (timeElapsed < duration) requestAnimationFrame(animation);
}

requestAnimationFrame(animation);
}
```

Mess with the `duration` and easing function to tweak it.

Messages In This Thread



Users browsing this thread: 1 Guest(s)