Scroll-to-Top Button using Vanilla JS
In this tutorial, you’ll learn how to create a scroll-to-top button.
Introduction
Creating a scroll-to-top button with smooth scrolling.
Plan
- Detect user scroll
- Display scroll-to-top button after a certain amount of time
- Go to the top when the user clicks on it
Detect user scroll
How to detect user scroll?
First, we create a function called handleScroll() in this function we detect the user scroll.
we need to access the document elements for this case we use document.documentElement(). this returns all the elements used in the page.
using rootElement variable we can detect scroll status.
we need to detect Scroll Top status how much space our scroll runs.
Now we need to find the total amount of scroll for this case we have ScrollHeight and ClientHeight.
ScrollHeight includes the invisible part of the scroll but the clientHeight includes the visible part of Scroll.
We need to subtract clientHeight from ScrollHeight to find the totalScroll.
After this, we need to divide scrollTop by totalScroll which remains an amount.
Now we add our logic to the document.
And now we want to go to top of the page.
We create a function scrollTop in this function we use ScrollTo this requires at least one parameter if you want to add smooth scroll then you can.
and it’s all.