1

I'm trying to call a CSS animation on the event that this button is pressed, after doing some research it seems classList is the way forward. It's late and I think I'm being stupid but I cannot get it to work.

HTML:

<body>
<img id="myID" class="mouse" src="mouse.png" onclick="ani()">
<script src="script.js"></script>
</body>

<head>
<link href="styles.css" rel="stylesheet"/>
</head>

JavaScript:

function ani()
{
  document.getElementById('myID').classList.add = 'animate';
}    

CSS:

.animate
{
  animation: test 1s linear forwards;
}
@keyframes test
{
  100%
{
  transform: translateX(calc(8%));
}
}

1 Answer 1

2

add is a function so the way you are using classList needs a slight change from:

document.getElementById('myID').classList.add = 'animate';

to:

document.getElementById('myID').classList.add('animate');

function ani(){
  document.getElementById('myID').classList.add('animate');
}    
.animate {
  animation: test 1s linear forwards;
}

@keyframes test {
  100% {
    transform: translateX(calc(8%));
  }
}
<body>
    <img id="myID" class="mouse" src="https://stock.wikimini.org/w/images/d/d4/Mickey_Mouse.png" onclick="ani()">
</body>

    

Sign up to request clarification or add additional context in comments.

2 Comments

Still having no luck unfortunately.. I feel like I'm missing something really simple.
someone has kindly added a snippet to show what happens. Could you try that and then describe what isn't working for you? One thing is, are you expecting a second click to do something animation-wise?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.