Solution 1 :

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>

Problem :

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>

Comments

Comment posted by donipeter

Oh My God Thank you very much. I studied a lot for 2 days to solve this problem. However, I haven’t solved this problem. Finally, we decided to ask the ‘StackOverflow’ community. I was giving up, but you let me regenerate. Thank you.

Comment posted by Kharel

@donipeter, no worries. btw you could improve the logic. your current logic keeps adding keyframe ruleset. you could extract that to different method and run only once. Also if you could upvote and accept my answer would be great.

Comment posted by Masoud Keshavarz

You also needn’t to add and remove

By