Search code examples
javascriptcssanimationcss-animationsopacity

How can I create a CSS animation in JavaScript?


How can I create the CSS animation below in JavaScript? I've looked all over Google, and tried multiple times to create this but I couldn't figure out how to do this.

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 100;
  }
}

To run this, I know I can use what is shown below, but I don't know how to create this animation. Can anyone help?

element.style.animation = "fadeIn 5s linear";

Solution

  • You can use javascript with transition to achieve it

    // start frame
    const start = {
      opacity: 0
    };
    
    // end frame
    const end = {
      opacity: 1
    };
    
    const element = document.querySelector('span');
    Object.assign(element.style, start);
    element.style.transition = 'all 5s linear';
    
    requestAnimationFrame(() => {
      Object.assign(element.style, end);
    });
    <span>Lorem Ipsum</span>