donipeter
donipeter

Reputation: 21

Reset JavaScript animation

This source code is part of the web page I am studying. I implemented the animation effect. However, I found the problem not to repeat.

The problem is the initial state of the animation. The initialization state was implemented. However, the problem is not solved.

Click inside the div.main tag to animate, but it animates only once. Since it is part of the source code, the if() statement is entered. Because of this, I want to solve it in a function.

function Reset() {
    var main_Selector = document.querySelector(".main");
    main_Selector.style.animation = 'anim 0.5s ease-in forwards';
    document.styleSheets[0].insertRule('\
        @keyframes anim {\
                from { background : greenyellow; }\
                to   { background : floralwhite; }\
        }'
    );       
    main_Selector.classList.remove("main");
    void main_Selector.offsetWidth;
    main_Selector.classList.add("main"); 
}
.main {
    overflow: hidden;
    width: 330px;
    height: 100px;
    border: 2px dashed mediumpurple;
    background-color:floralwhite;
    animation-direction:alternate;
}
<div class="main" onclick="Reset()"></div>

Upvotes: 1

Views: 52

Answers (1)

Kharel
Kharel

Reputation: 827

function Reset() {
    var main_Selector = document.querySelector(".main");
    main_Selector.style.animation = '';
    setTimeout(() => { main_Selector.style.animation = 'anim 0.5s ease-in forwards'}, 0);
    document.styleSheets[0].insertRule('\
        @keyframes anim {\
                from { background : greenyellow; }\
                to   { background : floralwhite; }\
        }'
    );       
    main_Selector.classList.remove("main");
    void main_Selector.offsetWidth;
    main_Selector.classList.add("main"); 
}
.main {
    overflow: hidden;
    width: 330px;
    height: 100px;
    border: 2px dashed mediumpurple;
    background-color:floralwhite;
    animation-direction:alternate;
}
<div class="main" onclick="Reset()"></div>

Upvotes: 2

Related Questions