Home > Enterprise >  How to get to the top of page without scrolling
How to get to the top of page without scrolling

Time:11-13

This problem has troubled me for a long time: I want the page to reach the top without scrolling.

I tried this, but it didn’t work:

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

CodePudding user response:

you need both x-coord and y-coord

Try this

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

CodePudding user response:

if your aim is to avoid the actual scrolling (the "animation"), use behavior: 'instant'.

const button = document.getElementById('instant-top-button')
button.addEventListener('click', () => window.scrollTo({
  top: 0,
  behavior: 'instant',
}))
<p>scroll down &#11123;</p>
<p>
  <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</p>
<button id="instant-top-button">&#11121; to top, instantly!</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

please, try a simple solution. Just replace your code for this here:

window.scroll(0, 0);

Cheers, Marcelo

  • Related