This Back To Top Button code that I discovered online is quite effective on my website.
// Defining a variable for the button element.
const scrollToTopButton = document.getElementById('js-top');
// Creating a function to display our scroll-to-top button when scrolling beyond the initial window height.
const scrollFunc = () => {
// Getting the current scroll value
let y = window.scrollY;
// Adding a class to the scroll-to-top button based on scroll location
if (y > 100) {
scrollToTopButton.className = "top-link show";
} else {
scrollToTopButton.className = "top-link hide";
}
};
window.addEventListener("scroll", scrollFunc);
const scrollToTop = () => {
// Setting up a variable for the distance from top of document.
const c = document.documentElement.scrollTop || document.body.scrollTop;
// Scrolling back to top with animation using requestAnimationFrame
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
// ScrollTo takes x and y coordinates. Adjust speed by changing '10' value.
window.scrollTo(0, c - c / 10);
}
};
// Running ScrolltoTop function on button click
scrollToTopButton.onclick = function(e) {
e.preventDefault();
scrollToTop();
}
However, whenever I try to add smooth scrolling for better user experience:
html {
scroll-behavior: smooth;
}
The back-to-top button starts glitching.
I wish to have the back-to-top button also smoothly scroll along with the rest of the content on the page, including anchor links in the navigation linking to sections on the same page.