GSAP animation won’t work unless HTML containing the animation isn’t in the viewport while rendering?

Viewed 17

This is the site I’m building https://andersonwater.cmsmax.com/

If you load/render the page normally from the top and scroll down to the animation section, the animation won’t work

If you load/render the page while already scrolled down to that section the animation will work

Quite strange...

And here is the code snippet that I'm using

(function() {
    class HoverButton {
        constructor(el) {
            this.el = el;
            this.hover = false;
            this.attachEventsListener();
            this.calculatePosition();
        }

        attachEventsListener() {
            window.addEventListener('mousemove', e => this.onMouseMove(e));
            window.addEventListener('resize', e => this.calculatePosition(e));
        }

        calculatePosition() {
            gsap.set(this.el, {
                x: 0,
                y: 0,
                scale: 1
            });
          
            const box = this.el.getBoundingClientRect();
            this.x = box.left + (box.width * 0.5);
            this.y = box.top + (box.height * 0.5);
            this.width = box.width;
            this.height = box.height;
        }

        onMouseMove(e) {
            let hover = false;
            let hoverArea = (this.hover ? 0.7 : 0.5);
            let x = e.clientX - this.x;
            let y = e.clientY - this.y;
            let distance = Math.sqrt(x * x + y * y);
          
            if (distance < (this.width * hoverArea)) {
                hover = true;
                if (!this.hover) {
                    this.hover = true;
                }
                this.onHover(e.clientX, e.clientY);
            }

            if (!hover && this.hover) {
                this.onLeave();
                this.hover = false;
            }
        }

        onHover(x, y) {
            gsap.to(this.el, {
                x: (x - this.x) * 0.4,
                y: (y - this.y) * 0.4,
                scale: 1.15,
                ease: 'power2.out',
                duration: 0.4
            });
            this.el.style.zIndex = 10;
        }
        onLeave() {
            gsap.to(this.el, {
                x: 0,
                y: 0,
                scale: 1,
                ease: 'elastic.out(1.2, 0.4)',
                duration: 0.7
            });
            this.el.style.zIndex = 10;
        }
    }

    const btn1 = document.querySelector('.under-splash__item--left>div:first-child');
    new HoverButton(btn1);

    const btn2 = document.querySelector('.under-splash__item--right>div:first-child');
    new HoverButton(btn2);

    const btn3 = document.querySelector('.products__item--air-purification>img');
    new HoverButton(btn3);

    const btn4 = document.querySelector('.products__item--hvac-services>img');
    new HoverButton(btn4);
})();

Any solutions? Thanks.

0 Answers
Related