Animate() doesn't work

Hello everyone. I’m currently doing a task related to animation using animate() in DOM. I’ve got a div in html and my task it to animate it to the left or right when button is pressed.

  1. I created a div with styles
  2. I got id of that div using getElementById() and placed it to variable
  3. I added eventListener to the variable and need to animate it to the right or left
    code is below:
let animation = document.getElementById('animate');
animation.addEventListener('keydown', () => {
      direction: reverse,
      direction: normal,

css styles

      #animate {
        width: 200px;
        height: 200px;
        background-color: red;
        margin: auto;

Thanks in advance for your time and help!

  1. You closed the method ) before the second object.

  2. The first argument is the keyframe object (or array of objects). It is for the properties and value you want to animate. The second argument is the options, which is either a numeric value or an object with the “configurations” properties like duration, direction and so on.

Example code from MDN:

  // keyframes
  { transform: 'translateY(0px)' },
  { transform: 'translateY(-300px)' }
], {
  // timing options
  duration: 1000,
  iterations: Infinity
1 Like

There aren’t any keyframes there. Animation is changing one or several values (position, colour, etc) over time. You go from one to another. The first argument needs to be an array of keyframes:

Ah, snap

1 Like

@lasjorg thanks I will go through documentation one more time, I’m new to programming, it’s taking too much time to do simple animation((

@DanCouper thank you for for help and time, I will revise documentation

1 Like

You can do animations without JS, or at least just by adding and removing CSS classes. But it depends on the use case.

I figured it out @DanCouper @lasjorg

let animation = document.getElementById('animate');
document.addEventListener('keydown', () => {
      // keyframes
      { transform: 'translateX(0px)' },
      { transform: 'translateX(200px)' },
      // timing options
      duration: 1000,
      iterations: Infinity,

Now everything works
Thanks for your time and help!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.