Reputation: 49
I found a "Back to Top" effect written in JavaScript. But there's something in the code I don't understand.Thanks a lot!
window.onload = function () {
var oBtn = document.getElementById('btn1');
var timer=null;
oBtn.onclick= function () {
timer=setInterval(function () {
var scrollTop = document.documentElement.scrolltop || document.body.scrollTop;
var iSpeed = Math.floor(-scrollTop/8);//what does this mean?
if(scrollTop===0)
{
clearInterval(timer);
}
document.body.scrollTop = document.documentElement.scrollTop = scrollTop + iSpeed;
}, 30);
};
};
Upvotes: 1
Views: 57
Reputation: 103
iSpeed
is best thought of as a velocity. As the document scrolls back upwards, it gets set to that velocity which gradually becomes smaller as it gets closer to the targeted element.
Math.floor(-scrollTop/8)
In this case, you're constantly scrolling up an 1/8th of the distance between your position and that element.
Upvotes: 1
Reputation: 5188
-scrollTop
means 0-scrollTop
.
-scrollTop/8
means 0-scrollTop
divided by 8.
Math.floor()
rounds down to the nearest whole number.
Upvotes: 1