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