DEV Community

Rahul kumar
Rahul kumar

Posted on

How to add scroll to Top

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>
Enter fullscreen mode Exit fullscreen mode

Watch scroll

window.onscroll = () => {
      if (
        document.body.scrollTop > 20 ||
        document.documentElement.scrollTop > 20
      ) {
        // show button
      } else {
        // hide button
      }
    };
Enter fullscreen mode Exit fullscreen mode

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
  };
Enter fullscreen mode Exit fullscreen mode

live-demo

Top comments (1)

Collapse
 
ksengine profile image
Kavindu Santhusa