There is nothing wrong with the functionality of classList, instead I made a few changes to the code, as shown below,
<script> function debounce(func, wait , immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }; const sliderImages = document.querySelectorAll('.slide-in'); function checkSlide(e) { sliderImages.forEach(sliderImage => { const slideInAt = (window.scrollY + window.innerHeight) - (sliderImage.clientHeight / 2); const imageBottom = sliderImage.offsetTop + sliderImage.clientHeight; const isHalfShown = slideInAt > sliderImage.offsetTop; const isNotScrolledPast = window.scrollY < imageBottom; if(isHalfShown && isNotScrolledPast) { sliderImage.classList.add('active'); } else { sliderImage.classList.remove('active'); } }) } var myEfficientFn = debounce(function() {checkSlide();}, 20,true); window.addEventListener("scroll", myEfficientFn); </script>
- I put the
<script> tag inside the <body> . - In the checkSlide function, I replaced using the
height property with clientHeight - And finally, I returned the debounce function, as shown in the last line of code, instead of calling the function, because when the code looked like this
window.addEventListener('scroll', debounce(checkSlide)); , the debounce function called when the window loaded called the function was used. When we use the code window.addEventListener("scroll", function(){return debounce(checkSlide);}); , a function is assigned to this event and is called every time this event occurs.
source share