I have a navigation bar to scroll down to anchor elements. The navbar is inside the body.
My css :
body {
scroll-behavior: smooth;
}
In the page, I also use some javascript. One is a javascript with the following function to navigate to other page elements :
window.scroll({
top : pos,
left : 0,
behavior : 'smooth'
});
With Chrome, when I call the javascript function, the scroll is smooth. But when I navigate to anchors through navigation bar links, it is not smooth.
Would someone care to explain me why ?
Also with Firefox both scroll from navigation bar & javascript function are smooth. I think it's a bit wierd that one work but not the other.
EDIT : my workaround is as follow (vanilla JS / works with all modern browsers) :
let pos = document.querySelector(element).offsetTop;
if ('scrollBehavior' in document.documentElement.style) { //Checks if browser supports scroll function
window.scroll({
top : pos,
left : 0,
behavior : 'smooth'
});
} else {
smoothScrollTo(0, pos, 500); //polyfill below
}
And the fallback scroll function :
window.smoothScrollTo = function(endX, endY, duration) {
let startX = window.scrollX || window.pageXOffset,
startY = window.scrollY || window.pageYOffset,
distanceX = endX - startX,
distanceY = endY - startY,
startTime = new Date().getTime();
// Easing function
let easeInOutQuart = function(time, from, distance, duration) {
if ((time /= duration / 2) < 1) return distance / 2 * time * time * time * time + from;
return -distance / 2 * ((time -= 2) * time * time * time - 2) + from;
};
let timer = window.setInterval(function() {
let time = new Date().getTime() - startTime,
newX = easeInOutQuart(time, startX, distanceX, duration),
newY = easeInOutQuart(time, startY, distanceY, duration);
if (time >= duration) {
window.clearInterval(timer);
}
window.scrollTo(newX, newY);
}, 1000 / 60); // 60 fps
};