Detecting scroll
For the back up button in Personal Website
- Store the
scrollY
value of the window in a variable. - Listen for the scroll event on the window object.
- When the page scroll happens, compare the previous
scrollY
value with the currentscrollY
. - If the current value is greater than the old value, then the scroll direction is downwards. Otherwise, the scroll direction is upwards.
- Update the current scroll position to the variable.
// Initial state
var scrollPos = 0;
// adding scroll event
window.addEventListener('scroll', function(){
// detects new state and compares it with the new one
if ((document.body.getBoundingClientRect()).top > scrollPos)
document.getElementById('info-box').setAttribute('data-scroll-direction', 'UP');
else
document.getElementById('info-box').setAttribute('data-scroll-direction', 'DOWN');
// saves the new position for iteration.
scrollPos = (document.body.getBoundingClientRect()).top;
});
[source](Simple JS scroll-direction detection) or this example:
var oldScrollY = window.scrollY;
var directionText = document.getElementById('direction');
window.onscroll = function(e) {
if(oldScrollY < window.scrollY){
directionText.textContent = " Down";
} else {
directionText.textContent = " Up";
}
oldScrollY = window.scrollY;
}