To implement a smooth scroll back to the top using vanilla JavaScript, you can use the window.requestAnimationFrame()
method for smoother animation. Here's an example code snippet to achieve this:
index.tsx403 chars14 lines
In the above code:
scrollToTop()
is a recursive function that animates the scroll back to top by gradually decreasing the scroll position until it reaches the top.requestAnimationFrame()
method is used to perform the animation within the browser's rendering cycle for smooth scrolling.scrollToTopBtn
is clicked, it triggers the scrollToTop()
function.Make sure to update scrollToTopBtn
with the actual id of your button in the HTML.
Remember to add this script in your HTML file, preferably at the end before the closing body tag, or wrap it inside a DOMContentLoaded event listener to ensure the DOM is fully loaded before executing the script.
gistlibby LogSnag