Q:

javascript scroll to top of page

// Get The Id
var topPage = document.getElementById(`top-page`)

// On Click, Scroll to the Top of Page
topPage.onclick = () => window.scrollTo({ top: 0, behavior: 'smooth' })

// On scroll, Show/Hide the button
window.onscroll = () => {
  window.scrollY > 500
    ? (topPage.style.display = 'block')
    : (topPage.style.display = 'none')
}

// CSS
body {
    background-color: #111;
    height:5000px;
}


#top-page {
  width: 50px;
  position: fixed;
  right: 30px;
  bottom: 30px;
  cursor: pointer;
  color: white;
  display: none;
}
// HTML
<img id="top-page" src="https://svgshare.com/i/LW3.sv" alt="Top">
3
window.scroll({
 top: 0, 
 left: 0, 
 behavior: 'smooth' 
});
4
//Instant scroll to top of page
window.scrollTo(0, 0);
2
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0; // For Safari
  document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
1
window.scrollTo(x-coord, y-coord);
0

New to Communities?

Join the community