Hi everyone,
I’m trying to slow down an animation that I created with JS. I’m currently using the “smooth” property for the “.scrollIntoView” function, the thing is that I want it to go slower than that. I think I could be possible to create a custom JS function to slow it down, but I’m not sure. My JS knowledge is pretty much null.
Thank you so much for the help in advance,
Pablo
<script>
// Auto scrool after 4 secs delay
const myTimeout = setTimeout(myAutoScroll, 4000);
function myAutoScroll() {
//with scrollTop we check if the page has been scrolled
//if == 0, it hasnt
if ($(window).scrollTop() == 0){
document.getElementById('scrollcard').scrollIntoView({behavior: "smooth"});
}
}
</script>
Here is my site Read-Only: [LINK]
Here is the published version to see the animation in action after 4 seconds (https://xl-animation-test.webflow.io/)
Hi Pablo! I’m waaaay late to the party, but this post has so many views it seems like a good idea to follow up for future readers.
Okay… so you want to slow down the smooth scrolling animation beyond what the built-in .scrollIntoView({behavior: "smooth"}) provides. You’re right that we’ll need a custom solution since the native smooth scrolling doesn’t allow speed customization.
Here’s a custom implementation that will give you control over the scrolling speed:
// Custom slow scroll function
function slowScrollTo(element, duration = 2000) {
// Get the element's position relative to the viewport
const elementPosition = element.getBoundingClientRect().top;
// Get starting position (current scroll position)
const startPosition = window.pageYOffset;
// Calculate distance to scroll
const distance = elementPosition;
let startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const scrollY = easeInOutCubic(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, scrollY);
if (timeElapsed < duration) {
requestAnimationFrame(animation);
}
}
// Easing function for smooth acceleration and deceleration
function easeInOutCubic(t, b, c, d) {
t /= d/2;
if (t < 1) return c/2*t*t*t + b;
t -= 2;
return c/2*(t*t*t + 2) + b;
}
requestAnimationFrame(animation);
}
// Updated auto scroll function
const myTimeout = setTimeout(myAutoScroll, 4000);
function myAutoScroll() {
if ($(window).scrollTop() == 0) {
// Replace scrollIntoView with custom function
// Increase the duration (ms) to make it slower (e.g., 3000 for 3 seconds)
slowScrollTo(document.getElementById('scrollcard'), 3000);
}
}
You can adjust the duration parameter (currently set to 3000 milliseconds or 3 seconds) to make the animation slower or faster. The higher the number, the slower the animation.