Last active
June 18, 2021 20:57
-
-
Save moinism/a4d4fa5d47f205efaf56 to your computer and use it in GitHub Desktop.
Page Scroll Progress With JavaScript
This file contains hidden or 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
// Read more about it here: https://lab.moin.im/2015/03/18/page-scroll-progress/ | |
function scrollProgress (el, updateFunc, endFunc) { | |
document.addEventListener('DOMContentLoaded', function() { | |
var progress = 0, | |
end = false, | |
timeStart = null, | |
timeEnd = null, | |
height = 0, | |
elt = null; | |
if( el == window ) { | |
el = document.body; | |
elt = window; | |
height = window.innerHeight; | |
} else { | |
el = document.getElementById(el); | |
elt = el; | |
height = el.clientHeight; | |
} | |
elt.addEventListener('scroll', function() { | |
if(timeStart == null) | |
timeStart = Date.now(); | |
progress = (el.scrollTop / ( el.scrollHeight - height ) ) * 100; | |
updateFunc( progress ); | |
if(progress >= 100 && !end) { | |
timeEnd = Date.now(); | |
end = true; | |
endFunc( timeEnd - timeStart ); | |
} | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment