# JavaScript makes it easy to go back to the top of the page

• 2020-03-29 23:41:50
• OfStack

Many web pages have a "back to the top" button at the bottom, especially if there is no navigation at the bottom of the page, which can help the visitor find the navigation again or revisit the AD (beautiful thought). As JavaScript has become more and more widely used in recent years, the sliding effect has become ubiquitous, so I followed suit and made the back to top function a sliding effect. Later, in order to better fit the physical characteristics, the modification made the sliding effect of deceleration.
To start with, we get the distance between the scroll bar and the top of the page, and then we move it up a certain distance. Gets the distance between the scroll bar and the top of the page, moving it up a certain distance (a little less than the last time); And so on...
``````
<script type="text/javascript">

function goTop(acceleration, time) {
acceleration = acceleration || 0.1;
time = time || 16;

var x1 = 0;
var y1 = 0;
var x2 = 0;
var y2 = 0;
var x3 = 0;
var y3 = 0;

if (document.documentElement) {
x1 = document.documentElement.scrollLeft || 0;
y1 = document.documentElement.scrollTop || 0;
}
if (document.body) {
x2 = document.body.scrollLeft || 0;
y2 = document.body.scrollTop || 0;
}
var x3 = window.scrollX || 0;
var y3 = window.scrollY || 0;

//The horizontal distance from the scroll bar to the top of the page
var x = Math.max(x1, Math.max(x2, x3));
//The vertical distance from the scroll bar to the top of the page
var y = Math.max(y1, Math.max(y2, y3));

//The rolling distance is equal to the current distance/velocity, because the smaller the distance, the velocity is greater than 1, so the rolling distance is going to get smaller and smaller
var speed = 1 + acceleration;
window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));

//If the distance is not zero, continue to call the iterative function
if(x > 0 || y > 0) {
var invokeFunction = "goTop(" + acceleration + ", " + time + ")";
window.setTimeout(invokeFunction, time);
}
}
</script>
``````

Document. The documentElement. ScrollTop, document. Body. ScrollTop, window. ScrollY actually are the same, but they only play a role in some browsers. You can debug which ones work in which browsers.
How to use it?
``````
<a href="#" onclick="goTop();return false;">TOP</a>
``````

Related articles: