js window scroll to top code example

Example 1: Scroll to the top of the page using JavaScript?

// 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">

Example 2: scrool to top jquerry

$("a[href='#top']").click(function() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
  return false;
});

Example 3: js scrollto

element.scrollTo(x, y);
window.scrollTo(x, y);
element.scrollTo({
  top: 100,
  left: 100,
  behavior: 'smooth'
});

Tags:

Css Example