Why doesn’t my CSS animation trigger when toggling a class with JavaScript?
16:04 28 Nov 2025

I’m trying to animate a div when a button is clicked. The class is added correctly, but the animation doesn’t run. Here’s my minimal code:

function toggleBox() {
   document.getElementById("box").classList.toggle("animate");
}
#box {
  width: 100px;
  height: 100px;
  background: red;
  transition: transform 1s ease;
}

.animate {
  transform: translateX(200px);
}

javascript html css