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.
Just move the the event callback function to a separate function and pass the reference to second parameter to
addEventListenerfunction and execute it.