i am currently learning to do things with vanilla Javascript. No plugins, libraries or code snippets. I want to do things on my own, so that I understand 100% of what is happening.
I wrote a little script which checks, if a section of the page is in view.
Now, the script works as expected, but I was wondering, if I had accomplished the task in a good way. I am especially unsure about looping over the sections in a scroll event. I would love to get some feedback on this. Example page
Here is the code
(function () {
// Store all panels in variable
const panels = document.querySelectorAll(".panel");
// Window on load event
window.addEventListener("load", () => {
let scrollTop = window.scrollY;
let windowHeight = window.innerHeight;
let documentHeight = document.body.offsetHeight;
panels.forEach( panel => {
if(scrollTop == panel.offsetTop ){
panel.classList.add("is-visible");
}
});
}); // end of load event
// Window on scroll event
window.addEventListener("scroll", () => {
let scrollTop = window.scrollY;
let windowHeight = window.innerHeight;
let documentHeight = document.body.offsetHeight;
panels.forEach( panel => {
if(scrollTop >= panel.offsetTop - ( windowHeight / 2)){
panel.classList.add("is-visible");
} else {
panel.classList.remove("is-visible");
}
if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
panel.classList.remove("is-visible");
}
});
}); // end of scroll event
})();
APPENDIX
So I refactored the code as follows. I am still not sure about things like the IIFs.
(function(){
const panels = document.querySelectorAll(".panel");
let scrolling = false;
(function windowOnLoad () {
// Window on load event
window.addEventListener("load", () => {
let scrollTop = window.scrollY;
let windowHeight = window.innerHeight;
let documentHeight = document.body.offsetHeight;
panels.forEach( panel => {
if(scrollTop == panel.offsetTop ){
panel.classList.add("is-visible");
}
});
}); // end of load event
})();
(function windowOnSCroll(){
window.addEventListener("scroll", () => {
scrolling = true;
});
})();
setInterval( function() {
if (scrolling) {
scrolling = false;
let scrollTop = window.scrollY;
let windowHeight = window.innerHeight;
let documentHeight = document.body.offsetHeight;
panels.forEach( panel => {
if(scrollTop >= panel.offsetTop - ( windowHeight / 2)){
panel.classList.add("is-visible");
} else {
panel.classList.remove("is-visible");
}
if(scrollTop >= (panel.offsetTop + panel.clientHeight) - ( windowHeight / 2) ) {
panel.classList.remove("is-visible");
}
});
}
}, 250 );
})();