Scroll to top is a functionality provided in a website, where user can click on a button to move on the top of the page.
Without much time, let's see how can we do it
Add button
<Button
variant="unstyled"
pos="fixed"
bottom={5}
right={5}
fontSize="4xl"
onClick={moveToTop}
>
π
</Button>
Watch scroll
window.onscroll = () => {
if (
document.body.scrollTop > 20 ||
document.documentElement.scrollTop > 20
) {
// show button
} else {
// hide button
}
};
moveToTop
// When the user clicks on the button, scroll to the top of the document
const moveToTop = () => {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
};
Top comments (1)
You don't need js
How can you create a Scroll To Top button with just HTML?.
Kavindu Santhusa γ» Dec 24 γ» 2 min read