DOM Animations

Creating smooth animations with JavaScript

🎬 What are DOM Animations?

DOM animations allow you to create smooth visual effects by changing CSS properties over time using JavaScript.


// Simple animation example
const box = document.getElementById('myBox');
box.style.transition = 'transform 0.5s';
box.style.transform = 'translateX(100px)';
                                    

Try it:

Animation Methods

🎯

CSS Transitions

Smooth property changes

element.style.transition = 'all 0.3s';
element.style.opacity = '0.5';
🔄

requestAnimationFrame

Frame-by-frame animations

function animate() {
  // Animation logic
  requestAnimationFrame(animate);
}
⏱️

setInterval

Time-based animations

setInterval(() => {
  // Animation step
}, 16);
🎨

Web Animations API

Modern animation control

element.animate([
  {transform: 'scale(1)'},
  {transform: 'scale(1.2)'}
], 500);

🔹 Basic CSS Transition Animation

The easiest way to animate elements is using CSS transitions:

// Get the element
const button = document.getElementById('myButton');

// Add transition style
button.style.transition = 'background-color 0.3s, transform 0.2s';

// Animate on hover
button.addEventListener('mouseenter', () => {
    button.style.backgroundColor = '#e74c3c';
    button.style.transform = 'scale(1.1)';
});

button.addEventListener('mouseleave', () => {
    button.style.backgroundColor = '#3498db';
    button.style.transform = 'scale(1)';
});

Try it:

🔹 Fade In/Out Animation

Create smooth fade effects by changing opacity:

function fadeIn(element, duration = 500) {
    element.style.opacity = '0';
    element.style.transition = `opacity ${duration}ms`;
    
    setTimeout(() => {
        element.style.opacity = '1';
    }, 10);
}

function fadeOut(element, duration = 500) {
    element.style.transition = `opacity ${duration}ms`;
    element.style.opacity = '0';
}

// Usage
const text = document.getElementById('fadeText');
fadeIn(text);

Try it:

This text will fade!

🔹 Slide Animation

Create sliding effects using transform properties:

function slideIn(element) {
    element.style.transform = 'translateX(-100%)';
    element.style.transition = 'transform 0.5s ease-in-out';
    
    setTimeout(() => {
        element.style.transform = 'translateX(0)';
    }, 10);
}

function slideOut(element) {
    element.style.transition = 'transform 0.5s ease-in-out';
    element.style.transform = 'translateX(100%)';
}

// Usage
const panel = document.getElementById('slidePanel');
slideIn(panel);

Try it:

Sliding Panel

🧠 Test Your Knowledge

Which CSS property is commonly used for smooth animations?