javascriptanimation

Pause asynchronous animation on hover


I want the animation of the hovered ball to pause, others should keep animating. Chat GPT has no clue. According to css hover should also reveal the 2nd image - > this only works when i remove javascript altogether.

Here's the codepen

const balls = document.querySelectorAll('.ball');

// Function to animate the sway of a ball
function swayBall(ball, offsetAngle) {
    const amplitude = Math.random() * 1 + 1; 
    const speed = Math.random() * 0.02 + 0.01; 

    let angle = offsetAngle; 
    let isHovered = false; 
    let animationId; // 

    function animate() {
        if (!isHovered) {
            angle += speed; 
            const swayAngle = Math.sin(angle) * amplitude; 
            ball.style.transform = `rotate(${swayAngle}deg)`; 
        }
        animationId = requestAnimationFrame(animate); 
    }

    // Start animation
    animate();

    // Stop animation on hover
    ball.addEventListener('mouseenter', () => {
        isHovered = true; // Stop animation
        cancelAnimationFrame(animationId); 
        ball.style.transform = ''; 
        console.log(`Hover started on:`, ball); 
    });

    // Resume animation on mouse leave
    ball.addEventListener('mouseleave', () => {
        isHovered = false; 
        animate(); 
        console.log(`Hover ended on:`, ball); 
    });
}

balls.forEach((ball, index) => {
    const offsetAngle = Math.random() * Math.PI * 2; 
    swayBall(ball, offsetAngle);
});

Animation works fine, but it does not stop on hover, nor does it reveal the image below.


Solution

  • that's happening because "hanging-balls" div has no height at all. So in reality you are not hovering to the balls. you could just give it a fixed height or 100%. I'm pretty sure that's the problem