Home > Enterprise >  Snap instantly to top of page?
Snap instantly to top of page?

Time:09-14

Is there a way to instantly snap to the top of the page without scrolling, when pressing a button? I saw that there are a few ways to scroll to the top, but they are always kinda smooth-scroll.

CodePudding user response:

Here's how to do it:

// the button is stored in the variable topScroll
// the first parameter in scrollTo is x axis and second is y
topScroll.onclick = () => window.scrollTo(window.scrollX, 0);

//If you don't want to manipulate scrollX
topScroll.onclick = () => window.scrollTo(window.scrollX, 0);

tell me if this works

CodePudding user response:

document.addEventListener("DOMContentLoaded", function(){
  
  // We get the Container Element, to prepend some random Elements to increase the Length.
  const containerEl = document.getElementById('container')
  
  // Loop to insert 100 paragraph elements with random Number
  for(let i = 0; i < 100; i  ){
    const newEl = document.createElement('p');
    newEl.innerText = Math.floor(Math.random()*1000000);
    
    containerEl.prepend(newEl);
  }
  
  // We create a Header Element for the Top page
  const titleEl = document.createElement("h1");
  titleEl.innerText = "U.S.S Enterprise";
  containerEl.prepend(titleEl);
  
  // We jump to the bottom of the Page
  const containerHeight = containerEl.offsetHeight;
  window.scrollTo(0, containerHeight);
  
  // We add a EventListener for the Button at the bottom of the Page
  document.getElementById('scrollTopBtn').addEventListener("click", function(){
  
    // When clicked, we jump to the top of the page
    // The User can set a default Behavior for scrolling in the Browser as Accessability 
    // Setting. If you dont override it, it defaults to auto and using this browser set 
    // Setting. Therefore we define the behavior as instant.
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: 'instant'
    });
  });
})
<div id="container">
  <button id="scrollTopBtn">Beam me up, Scotty!</button>
</div>

CodePudding user response:

Use this function when user click the button:

function scrollToTop(){
  document.documentElement.scrollTop = 0;
}
  • Related