Home > Software design >  How can I simplify my js code for css animation?
How can I simplify my js code for css animation?

Time:12-15

I made CSS animations and buttons to play the animations and use add and remove classes to play each motion. I didn't use a toggle because if I use a toggle, it mixes with other buttons.
I've seen many CSS animations that didn't use js at all.
Is there any way to reduce my js code and simplify it?

Here is the code-


    playbtn.addEventListener("click", function (e) {
        e.preventDefault;
        ball.style.display = "block";
        bowl.style.display = "none";

        ball.classList.remove("ball-move");
        ball.offsetWidth = ball.offsetWidth;
        ball.classList.add("ball-move");

        document.getElementById('dFace').className = '';
        dFace.offsetWidth = dFace.offsetWidth;
        dFace.classList.add("p-head-move");

        document.getElementById('ear').className = '';
        ear.offsetWidth = ear.offsetWidth;
        ear.classList.add("lean");

        document.getElementById("mouthid").className = '';
        mouth.offsetWidth = mouth.offsetWidth;
        mouth.classList.add("mouth-move");

    }, false);

CodePudding user response:

I think you have to read about Animation play state api, that will reduce your code. Doc Link!

CodePudding user response:

1, From your code, I assume that bowl, ball, dFace, ear and mouth are all HTMElement that have already assigned with a value from document.getElementById. So, you may not have to get the HTMLElement again in this functions.

2, You may not need to assign the value for offsetWidth as it is a read-only property as described in https://www.w3schools.com/jsref/prop_element_offsetwidth.asp. You can remove those lines.

  1. You might be missing () for e.preventDefault

I will suggest the followings:

playbtn.addEventListener("click", function (e) {
    e.preventDefault();
    ball.style.display = "block";
    bowl.style.display = "none";

    ball.classList.remove("ball-move");
    ball.classList.add("ball-move");

    dFace.className = '';
    dFace.classList.add("p-head-move");

    ear.className = '';
    ear.classList.add("lean");

    mouth.className = '';
    mouth.classList.add("mouth-move");
}, false);

Also, the action on dFace, ear and mouth are similar, so you may wrap it in a function call restartAnimation to further reduce duplications of your code.

const restartAnimation = (ele, className) => {
    ele.className = '';
    ele.classList.add(className);
}

playbtn.addEventListener("click", function (e) {
    e.preventDefault();
    ball.style.display = "block";
    bowl.style.display = "none";

    ball.classList.remove("ball-move");
    ball.classList.add("ball-move");

    restartAnimation(dFace, "p-head-move")
    restartAnimation(ear, "lean")
    restartAnimation(mouth, "mouth-move")

}, false);
  • Related