"Best way to implement js scroll to element smoothly?"
Hey folks!
I’ve been trying to get a smooth js scroll to element working on my site, but it either jumps or feels clunky.
I’ve tried `window.scrollTo()` with behavior: 'smooth', but it’s not consistent across browsers.
Any tips for a modern, reliable approach?
Also, is there a way to add custom easing or animations? Or am I stuck with the default smooth scroll?
Thanks in advance!
---
*P.S. If you’ve got a vanilla JS solution, even better. Trying to avoid libraries if possible.*
Yo! The default smooth scroll is kinda meh, right? For more control, try GSAP’s ScrollTo plugin. I know you said no libraries, but GSAP is lightweight and gives you insane easing options.
If you’re dead set on vanilla, here’s a quick hack:
```js
const scrollToEl = (element) => {
const targetPos = element.getBoundingClientRect().top + window.scrollY;
window.scrollTo({
top: targetPos,
behavior: 'smooth'
});
};
```
Not perfect, but better than nothing.
Honestly, the native js scroll to element is hit or miss. I’ve found that adding a tiny delay with `setTimeout` can help with the clunkiness.
```js
setTimeout(() => {
document.getElementById('yourElement').scrollIntoView({ behavior: 'smooth' });
}, 100);
```
Weird, but it works. For easing, you’d need to manually animate the scroll position using `window.scrollY` and a lerp function. Mozilla’s docs have a solid example.
If you’re dealing with inconsistent behavior, try checking if the browser supports smooth scroll first:
```js
const supportsSmoothScroll = 'scrollBehavior' in document.documentElement.style;
```
If not, fall back to a polyfill or a custom solution. For easing, you could use a bezier curve with `requestAnimationFrame`—there’s a cool demo on CodePen (just search "smooth scroll easing vanilla js").
Wow, thanks for all the suggestions! I tried the `scrollIntoView` with the polyfill, and it’s way better. Still a bit choppy on older Safari, but the custom `requestAnimationFrame` approach looks promising.
Quick Q: For the manual animation, how do you handle interruptions (like user scrolling mid-animation)? Should I add a cancel flag or something?
Also, GSAP seems cool—might give it a shot if the vanilla route gets too messy. Appreciate the help!
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.