Akish Joseph
Akish Joseph

Reputation: 3

Correct way to execute a function on onscroll event on page refresh and automatic browser scroll?

I have a function which executes on onscroll event and I noticed it doesn't execute when I refresh the page and the browser retains it's scroll position. So I was wondering do I need to explicitly call the function once or there's a better way to handle this. Here's my function: `

function homeSliderAnimation(){
        if(document.body.classList.contains('home')){
            window.addEventListener('scroll', function(){
                let y = window.scrollY;
                let intersect = document.querySelector('.mainNavigation').getBoundingClientRect().bottom;
                let position = document.querySelector('.home--slider').scrollHeight - window.pageYOffset;
                y >= 100 ? document.body.classList.add('scrolled') : document.body.classList.remove('scrolled');
                position <= intersect ? document.body.classList.add('addBg') : document.body.classList.remove('addBg');
            });
        }
        
    }
    homeSliderAnimation();

`

Well the only way I know to make this work is by explicitly calling the function once and then attaching the function on scroll event.

Upvotes: 0

Views: 113

Answers (1)

Mina
Mina

Reputation: 17584

Just move the the event callback function to a separate function and pass the reference to second parameter to addEventListener function and execute it.

function scrollEventHandler() {
    let y = window.scrollY;
    let intersect = document
        .querySelector(".mainNavigation")
        .getBoundingClientRect().bottom;
    let position =
        document.querySelector(".home--slider").scrollHeight -
        window.pageYOffset;
    y >= 100
        ? document.body.classList.add("scrolled")
        : document.body.classList.remove("scrolled");
    position <= intersect
        ? document.body.classList.add("addBg")
        : document.body.classList.remove("addBg");
}
function homeSliderAnimation() {
    if (document.body.classList.contains("home")) {
        window.addEventListener("scroll", scrollEventHandler);
        scrollEventHandler();
    }
}
homeSliderAnimation();

Upvotes: 0

Related Questions