Quiero que el color y el tamaño de un cuadro div se animen y vuelvan a sus valores originales cuando se hace clic en un botón. Aquí está mi ejemplo de código:
document.getElementById("andAction").addEventListener("click", function() { document.getElementById("box").classList.toggle("animi"); }) .thing { transform: translate(150px, 100px); } .box { background-color: #999; padding: 2px; color: black; width:20px; margin: 0 auto; text-align: center; color: #fff; } @keyframes blob { 0% { background-color: #999; } 50% { background-color: #F9086D; transform: scale(2); background-color: red; border-radius: 20px; } 100% { background-color: #999; } } .animi { animation-name: blob; animation-duration:3s; animation-iteration-count:1; } <button id="andAction" class="button">button</button> <div id="box" class="box">1</div> Mi problema es que lo estoy haciendo con alternar. Lo que significa que tengo que hacer clic dos veces la segunda vez. Otra variedad fue classList.add y luego eliminar nuevamente. Esto no conduce a ningún resultado porque la animación no se inicia para el usuario. lo único que podría hacer sería trabajar con tiempo de espera.
Tengo la sensación de que hay otra manera?
Puede escuchar el evento onanimationend para eliminar la clase cuando finaliza la animación sin depender de temporizadores que son más difíciles de mantener:
const boxElement = document.getElementById("box") boxElement.addEventListener('animationend', (e) => { // if the target it the box (it's triggered by animations on children too) // and the animation name is `blob` (it's triggered by any animation) // remove the class if (e.target === boxElement && e.animationName === "blob") { boxElement.classList.remove('animi'); } }) document.getElementById("andAction").addEventListener("click", function() { boxElement.classList.add("animi"); })Simplemente agregue algunos js para eliminar la clase automáticamente después de que finalice la animación y cambie su comportamiento inicial para no alternar sino simplemente agregar la clase. Puede lograrlo usando https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event .
const box=document.getElementById("box"); document.getElementById("andAction").addEventListener("click", function() { box.classList.add("animi"); }); box.addEventListener('animationend', () => { box.classList.remove("animi"); }); .thing { transform: translate(150px, 100px); } .box { background-color: #999; padding: 2px; color: black; width: 20px; margin: 0 auto; text-align: center; color: #fff; } @keyframes blob { 0% { background-color: #999; } 50% { background-color: #F9086D; transform: scale(2); background-color: red; border-radius: 20px; } 100% { background-color: #999; } } .animi { animation-name: blob; animation-duration: 3s; animation-iteration-count: 1; } <button id="andAction" class="button">button</button> <div id="box" class="box">1</div>