-1

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);
}
<button onclick="toggleBox()">Toggle</button>
<div id="box"></div>

New contributor
Ayush Raj is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
3
  • 6
    I moved your code to a stack snippet and it seems the animation works. Commented Nov 28 at 19:09
  • 3
    Your snippet is working fine for me. Have you used your browser's dev tools inspect facility to see what is going on? In particular, are there any messages in the console? Commented Nov 28 at 19:38
  • 1
    Your code is working for me. Check in the actual environment, it could be possible that your CSS class is overriding somehow. And also, check by adding transform: none; inside the .box class as the initial state. Commented Nov 28 at 20:19

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.