JavaScript custom lazy load not working quite right

I’m working on a custom lazy load script which will lazy load images and then add a custom class to a parent element which then triggers all of the custom css animations. I had it working perfectly, so I thought. But when I started loading the page with not all the images in the viewport on load, nothing happens to that element.


(() => {
    const initLazyMask = () => {
        const isImgInViewport = (img) => {
            const rect = img.getBoundingClientRect();
            return (
                rect.top >= 0 &&
                rect.left >= 0 &&
                rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
                rect.right <= (window.innerWidth || document.documentElement.clientWidth)
            );
        };

        const lazyMaskLoader = () => {
            const lazyParents = document.querySelectorAll('[data-lazy-mask]');
            let delay = 0;

            lazyParents.forEach((parent, i) => {
                const img = parent.querySelector('img');
				function add_mask(e, c) {
					m = document.createElement(e);
					m.classList.add(c);
					parent.appendChild(m) ;
				}
				

This is my code, which is in current state giving me codepen errors, but I’m hoping this won’t be the case much longer.
Link to the codepen is here :
Codepen Link

Any and all help appreciated.

if (document.querySelectorAll('img[data-src]').length === 0 && document.querySelectorAll('img[data-srcset]').length === 0) {

Your current version of the HTML has no data-src’s or data-srcset’s (it has srcs and srcsets), so the event removal code fires immediately.

Following your direction, I tried changing the html to use data-srcset instead of srcset (which prevented any of the elements getting the load complete class) and then undid that change and modified the javascript so that it was looking for srcset instead of data-srcset (which has the same exact outcome as the other attempt). I appreciate your direction a lot, I’m just sort of lost here. :slightly_frowning_face:

Well if you’re just using src/srcset… you’re not lazy loading anything. You’re just loading it. So… step 1 is figuring out what you’re actually trying to do with the code.