Created
August 6, 2018 14:47
-
-
Save yanekyuk/62002a51814dce102bc08fecec3fd86c to your computer and use it in GitHub Desktop.
Dead simpe pure JavaScript smooth scroll to top
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function scrollToTop () { | |
var val = document.body.scrollTop || document.documentElement.scrollTop // THIS ONE IS HOW MUCH THE PAGE IS SCROLLED DOWN | |
if (val > 1) { // if (val > 0) also works, BUT SINCE WE TAKE THE SQUARE ROOT OF THE VAL, WHEN THE VAL IS FLOAT, IT NEVERS REACHES TO ZERO (IN THIS CASE IT IS INTEGER) | |
window.scrollBy(0, -Math.sqrt(val * 0.125) * 2) // HERE YOU CAN PLAY WITH THE VALUES TO CUSTOMIZE THE SPEED. 0.125 AFFECTS THE SMOOTHNESS, 2 AFFECTS THE OVERALL SPEED | |
timeoutForScroll(true, 10) // OF COURSE YOU CAN CHANGE THE VALUE 10 TO CHANGE THE SPEED | |
} else { // IF THE WINDOW IS ONLY 1 PIXELS AWAY FROM THE TOP | |
windows.scrollBy(0, -1) // MAKE IT ZERO :D | |
timeoutForScroll(false) // STOP THE TIMEOUT WITH OPERATOR | |
} | |
} | |
function timeoutForScroll (operator, time) { //OPERATOR DECIDES WHAT TO DO, TIME AFFECTS SPEED (IN THIS EXAMPLE IT IS 10) | |
var timeout // DECLARE THE TIMEOUT | |
if (operator) { // IF TRUE SET THE TIMEOUT | |
setTimeout( () => { scrollToTop() }, time ) // WHEN THE TIMEOUT ENDS CALL THE FUNCTION AGAIN | |
} else { | |
clearTimeout(timeout) // KILL THE TIMEOUT | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment