Trying to get cumulative vertical scroll distance

Viewed 66

I'm trying to get the cumulative scroll distance of the user. If they change scroll direction, then the cumulative scroll is reset to the distance of their last scroll, otherwise (if same direction) the cumulative scroll distance increases. I want this figure so that I can hide and show the navbar on my site only after the user scrolls more than a few pixels. Otherwise it's too sensitive.

The code I have so far isn't working the way I expect. At times, the cumulative scroll value isn't increasing despite the scroll direction remaining the same, while at other times is begins to work properly. If anyone could shed some light on what I'm doing wrong here, I'd really appreciate it.

const showHideHeader = (function(){

const doc = document.documentElement;
const w = window;

const contactInfo = document.querySelector(".contact-info");

let prevScroll = w.scrollY || doc.scrollTop;
let curScroll;
let direction = 0;
let prevDirection = 0;
let cumulativeScroll = 0;
let distanceScrolled = 0;

const checkScroll = function() {

    curScroll = w.scrollY || doc.scrollTop;
    distanceScrolled = Math.abs(curScroll - prevScroll);
    console.log(`distance scrolled is ${distanceScrolled}`);

    if (curScroll > prevScroll) { 
    
        direction = 2;
    }
    else if (curScroll < prevScroll) { 
    
        direction = 1;
    }

    if (direction === prevDirection) {
        cumulativeScroll += distanceScrolled;
    } else if (direction !== prevDirection) {
        cumulativeScroll = distanceScrolled;
    }

    console.log(`cumulative scroll is ${cumulativeScroll}`);
    console.log(`direction is ${direction}`);

    if (cumulativeScroll > 10) {
        toggleHeader(direction, curScroll);
    }
  
    prevScroll = curScroll;
};

const toggleHeader = function(direction, curScroll) {
    if (direction === 2 && curScroll > 85) { 

        header.classList.add("home-hide");
        contactInfo.classList.add("hide");
        prevDirection = direction;
    } else if (direction === 1) {

        header.classList.remove("home-hide");
        contactInfo.classList.remove("hide");
        prevDirection = direction;
    }
};

window.addEventListener('scroll', checkScroll);

})();

0 Answers
Related