Can you post an example of you project and setup please
Also there are native css and js to scroll to an anchor.
css
#example {
scroll-behavior: smooth;
}
js
element.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
The one thing about them though is no adjustable speed.
But you can still do it natively and with a duration set:
Scroll to an element smoothly - HTML DOM
//==credit = https://htmldom.dev/scroll-to-an-element-smoothly/
//== MH added padding
const duration = 800;
const scrollToTarget = function (target,padding) {
const top = target.getBoundingClientRect().top - padding;
const startPos = window.pageYOffset;
const diff = top;
let startTime = null;
let requestId;
const loop = function (currentTime) {
if (!startTime) {
startTime = currentTime;
}
// Elapsed time in miliseconds
const time = currentTime - startTime;
const percent = Math.min(time / duration, 1);
window.scrollTo(0, startPos + diff * percent);
if (time < duration) {
// Continue moving
requestId = window.requestAnimationFrame(loop);
} else {
window.cancelAnimationFrame(requestId);
}
};
requestId = window.requestAnimationFrame(loop);
}
var scroll_to = element.getAttribute('scrollto_section')
var target = document.querySelector('[scrollPoint="' + scroll_to + '"]')
if (scroll_to != 'section1'){
scrollToTarget(target,200);
} else {
scrollToTarget(target,0);
}
Here I use addition attributes.
The scroll to buttons get additional attributes with a value of where to scroll to and the Anchor points get additional attributes for their anchor value.
The code gets the buttons additional attributes value and uses that to find the correct anchor point with the same value.
The code then scrolls to that with a set speed. I added a padding feature. The original webpage has a lot more stuff in it which I did not read.
smoothscrolling_MH1.hypetemplate.zip
(51.1 KB)
--- Extra tip
Now just had a look at the rest of the page above.
It mentions easing methods and gives a link to some functions.
The functions are easily converted to use in the code here.
for example:
function easeInOutBack(x: number): number {
const c1 = 1.70158;
const c2 = c1 * 1.525;
return x < 0.5
? (Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2
: (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2;
}
becomes :
const easeInOutBack = function(x) {
const c1 = 1.70158;
const c2 = c1 * 1.525;
return x < 0.5
? (Math.pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2
: (Math.pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2;
}
then the line
window.scrollTo(0, startPos + diff * percent);
becomes
window.scrollTo(0, startPos + diff * easeInOutBack(percent));