Animate Your JavaScript Web Apps Effortlessly  with Auto-Animate

Animate Your JavaScript Web Apps Effortlessly with Auto-Animate

ยท

4 min read

Integrating smooth transitions and animations into a web page offers numerous advantages that collectively enhance the overall user experience. At the same time adding transitions in every component of the application gets overwhelming, a bit tricky and repetitive. So to overcome such scenarios and to handle all the heavy lifting here comes auto-animate.

"AutoAnimate adds automatic animations to your JavaScript applications with a single line of code."

In this article, we will see how to add animation to our web application effortlessly with real-world examples. We will create a dome vue application and try to animate its components.

Let's create a fresh vue.js application npm create vite@latest, we will use the default HelloWorld component. Firstly let's pull tailwindcss cdn in the index.html file

// Index.html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + Vue + TS</title>
    <!-- use tailwind css cdn -->   
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>

Let's remove everything form App.js and just keep the HelloWorld component

// App.vue
<script setup lang="ts">
import HelloWorld from './components/HelloWorld.vue'
</script>

<template>
  <HelloWorld />
</template>

// HelloWorld.vue

<script setup lang="ts">
</script>

<template>
      <div>Hello world</div>
</template>

Now we will create a list of 100 items and add a button to shuffle them, add and remove the items from the list. For this, we will add the following code to our HelloWorld component.

<script setup lang="ts">
import { ref } from 'vue';

let numbers = ref(Array.from({ length: 100 }, (y, i) => i));
function shuffle() {
  numbers.value.sort(() => 0.5 - Math.random())
}
</script>

<template>
  <section class="flex flex-wrap gap-4 text-black">
    <div
     v-for="number in numbers" :key="number" v-text="number"
     class="bg-gray-200 w-12 h-12 flex items-center justify-center"/>
  </section>
  <div class="fixed bottom-4 right-4">
    <button class="bg-green-600 rounded text-white" @click="shuffle">
      Shuffle
    </button>
  </div>
</template>

The above code works fine but there is no animation so it's hard to see which item is moved where. So it's time to install the autoAnimate plugin to our project. Run npm install @formkit/auto-animate, this will install the plugin.

There are several ways to use the plugin. Let's see the direct way of using autoAnimate.

<script setup lang="ts">
import { ref, onMounted } from 'vue'; 
import autoAnimate from '@formkit/auto-animate';

  const listSection = ref()
let numbers  = ref(Array.from({ length: 100 }, (y, i) => i));
function shuffle() {
  numbers.value.sort(() => 0.5 - Math.random())
}
onMounted(() => {
  autoAnimate(listSection.value)
})
</script>

<template>
  <section ref="listSection" class="flex flex-wrap gap-4 text-black">
    <div
     v-for="number in numbers" :key="number" v-text="number"
     class="bg-gray-200 w-12 h-12 flex items-center justify-center"/>
  </section>
  <div class="fixed bottom-4 right-4">
    <button class="bg-green-600 rounded text-white" @click="shuffle">Shuffle</button>
  </div>
</template>

Here we have just imported the autoAnimate plugin import autoAnimate from '@formkit/auto-animate'; and we have referenced the dom for the list section. apply the animation inside onMounted method and it works like magic, you can see the demo below.

Okay, so the way it works is it will animate whether you update a Dom node, transition it, prepend, append or remove items. you can try adding items like below

<button class="bg-black rounded text-white" @click="numbers.unshift(101)" >Add</button>

For the next example, we will create a todo list and for the animation, we will use vue-directive, so first let's change our main.js file as below:

// main.js
import { createApp } from 'vue'
import { autoAnimatePlugin } from '@formkit/auto-animate/vue'

import './style.css'
import App from './App.vue'

createApp(App).use(autoAnimatePlugin).mount('#app')

Now we will create another component called Todos

<script setup lang="ts">
import { ref } from 'vue';

// Todo type definition
interface Todo {
    text: string;
    completed: boolean;
}

// Reactive state
const newTodo = ref('');
const todos = ref<Todo[]>([]);

// Methods
const addTodo = () => {
    if (newTodo.value.trim() !== '') {
        todos.value.push({ text: newTodo.value, completed: false });
        newTodo.value = '';
    }
};

const removeTodo = (index: number) => {
    todos.value.splice(index, 1);
};
</script>

<template>
    <div class="max-w-md mx-auto mt-8">
        <h1 class="text-2xl font-bold mb-4">Todo List</h1>

        <!-- Todo Input -->
        <div class="flex mb-4">
            <input v-model="newTodo" @keyup.enter="addTodo" type="text" class="border p-2 flex-grow"
                placeholder="Add a new todo..." />
            <button @click="addTodo" class="ml-2 bg-blue-500 text-white p-2">Add</button>
        </div>

        <!-- Todo List -->
        <ul v-auto-animate>
            <li v-for="(todo, index) in todos" :key="index" class="flex items-center justify-between rounded items-center bg-gray-100 text-black mb-2">
               <div>
                   <input type="checkbox" v-model="todo.completed" class="mx-2 bg-blue-400" />
                   <span :class="{ 'line-through': todo.completed }">{{ todo.text }}</span>
                </div>
                <span @click="removeTodo(index)" class="ml-2 p-2 cursor-pointer text-sm text-red-500">&times;</span>
            </li>
        </ul>
    </div>
</template>

In the above component, we have used vue directive v-auto-animate so there is no reactive reference initialization and no need to mount the element manually like the previous one.

If you need to replace the default animation keyframes with custom ones. It provides a function as the second argument of the autoAnimate function. This function will be called before every animation and must return a KeyframeEffect.


Conclusion

AutoAnimate is a hassle-free animation utility designed to effortlessly incorporate smooth transitions into your web application. Compatible with various JavaScript frameworks such as React, Solid, Vue, Svelte, and others, AutoAnimate seamlessly integrates with your existing codebase without the need for extensive configurations.

With just a single line of code, AutoAnimate automatically enhances your JavaScript applications by introducing fluid animations. Consider a list component, for instance, and observe the significant difference when AutoAnimate is applied to the wrapping element, as compared to the same component without this animation utility. Have fun with Auto-animate.

Happy Coding!!

ย