How do I make icon spin with JavaScript?

The following makes my icon spin in CSS:

#icon {
    animation: rotate 3s ease-out infinite;
    }
@keyframes rotate {
  0% {
    transform: rotate(-200deg)
  }
  100% {
    transform: rotate(360deg)
  }

But I want to make it a button so when someone taps on the icon, it spins with the CSS lines above (but removing “infinite”). I did a search for “css in javascript” but they are for simple things like changing a color. I don’t know how to add something more complex with multiple open/close curly braces like above.

You don’t add all the CSS using JavaScript. Define the animation as a class.

.spin {
  animation: rotate 3s ease-out;
}

@keyframes rotate {
  0% {
    transform: rotate(-200deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

Then just apply and remove that class use JavaScript.

const icon = document.getElementById('icon');
icon.addEventListener('click', () => {
  icon.classList.add('spin');
});
icon.addEventListener('animationend', ()=>{
	icon.classList.remove('spin');
});

Adding the class will start the animation. When the animation completes an animationend event will be emitted and you can then remove the class. Removing the class is necessary if you want to repeatedly trigger the animation. If you only want to trigger it once, you don’t need to remove the class.

4 Likes