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

14 Replies, 1788 Views

For a super simple JS scroll to element solution, I just tweak the `scrollTop` property with a loop and `setTimeout`. It’s not fancy, but it gets the job done:

```javascript
function smoothScrollTo(target) {
const element = document.querySelector(target);
let currentPos = window.pageYOffset;
const targetPos = element.offsetTop;
const distance = targetPos - currentPos;
const duration = 500;
let start = null;

function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
window.scrollTo(0, easeInOutQuad(progress, currentPos, distance, duration));
if (progress < duration) window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);
}

// Easing function (google "easing functions" for more options)
function easeInOutQuad(t, b, c, d) {
t /= d / 2;
if (t < 1) return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
```
A bit verbose, but super customizable!

Messages In This Thread



Users browsing this thread: 1 Guest(s)