Home > Blockchain >  How to jump to top of page when routing WITHOUT using scroll?
How to jump to top of page when routing WITHOUT using scroll?

Time:03-23

I'm building a React application where I have footer links that when clicked, take the user to the bottom of whatever page they're clicking. I want to change it so that when these links are clicked, the user is automatically taken to the top of the new page.

I already tried a solution of automatically scrolling to the top of the page, which WORKS, but the issue is that I have smooth scrolling set for my website because I have some buttons that scroll to certain parts of the page clicked, and I want that animation to be smooth. However, for this particular function, I don't want smooth scroll because I don't want the user to see that they were taken to the bottom of a page then scrolled up.

This is my current code:

useEffect(() => {
    window.scrollTo(0, 0)
}, [])

Is there any way I can accomplish this without using scroll so that I can avoid having to display the smooth scrolling behavior?

CodePudding user response:

You can try adding behaviour as instant in scrollTo function and do let me know if it works

useEffect(() => {
     window.scrollTo({
      top: 0,
      left: 0,
      behavior: "instant"
    });
}, [])

CodePudding user response:

window.scrollTo({
  top: 0,
  left: 0,
  behavior: 'auto'
});

Should hopefully remove the smooth action.

CodePudding user response:

document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

document.body.scrollTop = 0; // For Safari
  • Related