Aleksandre Bregadze
Aleksandre Bregadze

Reputation: 339

JS animation crushes

I am making an app where a checkbox controls if overlay appears on a screen or not. For making appearance and disappearance smooth I added animations.

#overlay{
    position:absolute;
    height: 100vh;
    width: 100vw;
    background-color: white;
    display:none;
    animation-name: none;
    animation-play-state: paused;
    animation-fill-mode: forwards;
    animation-duration: 1s;
    opacity: 0;
}

@keyframes appear {
    0%{opacity: 0}
    100%{opacity: 1}
}

@keyframes disappear {
    0%{opacity: 1}
    100%{opacity: 0}
}

Then here I call these animations using js.

function handleChange(checkbox) {
    const animation = document.getElementById("overlay");
    if(checkbox.checked === true){
        if (window.innerWidth < 846) {
            animation.style.display="block";
            animation.style.animationName="appear";
            animation.style.animationPlayState = "running";
            document.getElementById('overlay2').style.display="none";
            disableScroll();
        }
        return false;
    }else{
        animation.style.animationName="disappear";
        animation.style.animationPlayState="running";
        animation.addEventListener('animationend', () => {
            animation.style.display="none";
            document.getElementById("overlay2").style.display="block";
        })
        enableScroll();
        return false;
    }
}

Animation works perfectly when it is first checked and unchecked. However if I repeat this action and check the box for the second time it crushes. Maybe a little help? Thank you!

Upvotes: 0

Views: 62

Answers (1)

Jiho Lee
Jiho Lee

Reputation: 987

Because You've added event listener each times.

Solution:

function handleChange(checkbox) {
    const animation = document.getElementById("overlay");
    if(checkbox.checked === true){
        if (window.innerWidth < 846) {
            animation.style.display="block";
            animation.style.animationName="appear";
            animation.style.animationPlayState = "running";
            document.getElementById('overlay2').style.display="none";
            disableScroll();
        }
        return false;
    } else {
        animation.style.animationName="disappear";
        animation.style.animationPlayState="running";
        const singleEvent = () => {
            animation.style.display="none";
            document.getElementById("overlay2").style.display="block";
            animation.removeEventListener('animationend', singleEvent)
        };
        animation.addEventListener('animationend', singleEvent);
        enableScroll();
        return false;
    }
}

Upvotes: 2

Related Questions