1

I would like execute a transition when pressing a button for the webpage to slowly scroll back to the top of the page. I know how to execute a transition using a change in class, but in this instance, how would i do it?

document.documentElement.scrollTop = 0;
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
johnDoe
  • 709
  • 11
  • 29
  • 2
    Possible duplicate of [Cross browser JavaScript (not jQuery...) scroll to top animation](https://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation) – לבני מלכה Jul 26 '18 at 10:13

2 Answers2

9
document.body.scrollIntoView({behavior: 'smooth', block: 'start'});

Works also for any other DOM element. And for horizontal scrolling too.

Anarion
  • 1,048
  • 6
  • 16
  • it's a very convenient way. By the way, can you explain more parameter meanings of `scrollIntoView` – Guokas Jun 11 '20 at 02:34
  • Nice little working draft (experimental) API. Not as fine-grained usage as a library, but good out-of-the-box, jQuery alternative. No IOS and Safari support, and of course IE (doesn't support smooth scrolling, which is the point of this question), but nice toolbelt addition for quick demos. – Phil Tune Oct 28 '20 at 19:21
-2

You can use below code to move the top of the page.

// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("myBtn").style.display = "block";
  } else {
    document.getElementById("myBtn").style.display = "none";
  }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}
body {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 20px;
  background: #ffffff;
}

#myBtn {
  display: none;
  position: fixed;
  bottom: 20px;
  right: 30px;
  z-index: 99;
  background-color: red;
  color: white;
  cursor: pointer;
  padding: 15px;
  border-radius: 4px;
}

#myBtn:hover {
  background-color: #555;
}
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>
<div style="padding:30px">Scroll Down</div>
<div style="padding:30px 30px 700px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Kiran Ghatage
  • 407
  • 1
  • 8
  • 15
  • 1
    Hi, this doesn't answer how to _transition_ (i.e. animate the scroll), only how to snap to a value. But thank for for writing this out. – Phil Tune Oct 28 '20 at 19:12