How To Run Css Animation In Javascript

If you’ve ever wondered how to incorporate CSS animations in your JavaScript code, you’ve come to the right place! In this blog post, we’ll show you how to run CSS animations in JavaScript using a simple, step-by-step approach. This way, you can take advantage of the power and flexibility of JavaScript while still utilizing the beauty of CSS animations.

Step 1: Create a CSS animation

First, you’ll need to create a CSS animation. For this example, let’s make a simple fade-in animation. You can do this by defining a @keyframes rule in your CSS file:

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

Next, apply the animation to an element using a CSS class:

    .fade-in {
        animation: fadeIn 2s ease-in-out forwards;
    }
    

In the example above, we applied the fadeIn animation to any element with the fade-in class. The animation lasts 2 seconds, uses the ease-in-out timing function, and sets the forwards fill mode to retain the final state of the animation.

Step 2: Add the CSS class to an element using JavaScript

Now that we have our CSS animation and class set up, we can use JavaScript to add the fade-in class to an element, triggering the animation. Let’s say we have a button that will reveal a hidden paragraph when clicked:

    <button id="revealButton">Reveal hidden text</button>
    <p id="hiddenText" style="display: none;">This is the hidden text.</p>
    

To run the animation, we’ll add an event listener to the button that will show the hidden paragraph and add the fade-in class to it:

    document.getElementById('revealButton').addEventListener('click', function() {
        const hiddenText = document.getElementById('hiddenText');
        hiddenText.style.display = 'block';
        hiddenText.classList.add('fade-in');
    });
    

When the button is clicked, the hidden paragraph will be displayed with a smooth fade-in animation.

Step 3: Detect the end of the animation (optional)

If you want to execute some JavaScript code once the animation has finished, you can listen for the animationend event. For example, to remove the fade-in class after the animation is done:

    document.getElementById('hiddenText').addEventListener('animationend', function() {
        this.classList.remove('fade-in');
    });
    

Now you know how to run CSS animations in JavaScript! By combining the power of JavaScript with the elegance of CSS animations, you can create dynamic and engaging user experiences for your website.