Lesson 21: jQuery Animation

Master jQuery animation techniques with practical examples. Learn to create smooth animations, transitions, and interactive UI elements.

Understanding jQuery Animation

jQuery provides powerful animation capabilities that allow you to create dynamic, engaging user experiences. The animation methods can manipulate CSS properties to create smooth transitions and movements.

Key Animation Methods:
  • animate() - Perform custom animations
  • fadeIn()/fadeOut() - Fade elements in/out
  • slideDown()/slideUp() - Slide elements vertically
  • show()/hide() - Show/hide elements
  • toggle() - Toggle between show/hide
Method Description Example
animate() Performs custom animation of CSS properties $("div").animate({left: '250px'});
fadeIn() Gradually changes opacity to show element $("p").fadeIn(1000);
slideDown() Gradually reveals element with sliding motion $("#panel").slideDown();
show() Displays hidden elements $("img").show(500);
delay() Sets a delay between queued animations $("div").slideUp(300).delay(800).fadeIn(400);

Digital Dice Animation

Create a realistic dice rolling animation using jQuery's animation capabilities combined with JavaScript timing functions.

Example 21.1: Digital Dice Roller

Roll virtual dice with animation:

Roll the dice to see the result
// Dice roller implementation
let diceInterval;

$("#roll-dice-btn").click(function() {
    // Clear previous interval if exists
    if(diceInterval) clearInterval(diceInterval);
    
    // Start animation
    diceInterval = setInterval(() => {
        const dice1 = Math.floor(Math.random() * 6) + 1;
        const dice2 = Math.floor(Math.random() * 6) + 1;
        
        // Update dice visuals
        updateDice("dice1", dice1);
        updateDice("dice2", dice2);
    }, 100);
    
    // Stop animation after 2 seconds
    setTimeout(() => {
        if(diceInterval) clearInterval(diceInterval);
        const finalDice1 = Math.floor(Math.random() * 6) + 1;
        const finalDice2 = Math.floor(Math.random() * 6) + 1;
        updateDice("dice1", finalDice1);
        updateDice("dice2", finalDice2);
        $("#dice-result").text(`You rolled: ${finalDice1} and ${finalDice2} (Total: ${finalDice1 + finalDice2})`);
    }, 2000);
});

$("#stop-dice-btn").click(function() {
    if(diceInterval) clearInterval(diceInterval);
});

function updateDice(diceId, value) {
    const $dice = $(`#${diceId}`);
    $dice.empty();
    
    // Create dots based on dice value
    if (value === 1) {
        $dice.append('
'); } else if (value === 2) { $dice.append('
'); $dice.append('
'); } else if (value === 3) { $dice.append('
'); $dice.append('
'); $dice.append('
'); } else if (value === 4) { $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); } else if (value === 5) { $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); } else if (value === 6) { $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); $dice.append('
'); } // Show value in center $dice.append(`
${value}
`); }

Image Gallery Animation

Create a smooth image gallery transition using jQuery's fade methods.

Example 21.2: Fading Image Gallery

Cycle through images with a fade transition:

// Fading image gallery
let currentSlide = 0;
let autoPlayInterval;

function showSlide(index) {
    const slides = $(".gallery-slide");
    slides.removeClass("active");
    slides.eq(index).addClass("active");
    currentSlide = index;
}

$("#next-btn").click(function() {
    const slides = $(".gallery-slide");
    const nextSlide = (currentSlide + 1) % slides.length;
    showSlide(nextSlide);
});

$("#prev-btn").click(function() {
    const slides = $(".gallery-slide");
    const prevSlide = (currentSlide - 1 + slides.length) % slides.length;
    showSlide(prevSlide);
});

$("#auto-btn").click(function() {
    if (autoPlayInterval) {
        clearInterval(autoPlayInterval);
        autoPlayInterval = null;
        $(this).html(' Auto Play');
    } else {
        autoPlayInterval = setInterval(() => {
            $("#next-btn").click();
        }, 2000);
        $(this).html(' Pause');
    }
});

// Initialize gallery
showSlide(0);

Bouncing Ball Animation

Create a bouncing ball animation using jQuery's animate method with custom easing.

Example 21.3: Bouncing Ball

Animate a ball with bouncing physics:

Bounce!
// Bouncing ball animation
let isBouncing = false;
let bounceInterval;

function bounceBall() {
    if(isBouncing) return;
    isBouncing = true;
    
    const $ball = $("#bouncing-ball");
    const $container = $("#bouncing-container");
    const containerHeight = $container.height();
    const ballHeight = $ball.height();
    const maxHeight = containerHeight - ballHeight;
    
    // Reset position
    $ball.css({ top: 0, left: '50%' });
    
    // Define easing function for bounce effect
    $.easing.bounceEase = function (x, t, b, c, d) {
        if ((t /= d) < (1/2.75)) {
            return c*(7.5625*t*t) + b;
        } else if (t < (2/2.75)) {
            return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
        } else if (t < (2.5/2.75)) {
            return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
        } else {
            return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
        }
    };
    
    // Animation function
    function animateBounce() {
        $ball.animate(
            { top: maxHeight },
            {
                duration: 800,
                easing: "bounceEase",
                complete: function() {
                    $ball.animate(
                        { top: 0 },
                        {
                            duration: 800,
                            easing: "linear",
                            complete: animateBounce
                        }
                    );
                }
            }
        );
    }
    
    // Start bouncing
    animateBounce();
}

$("#bounce-btn").click(function() {
    if(!isBouncing) {
        bounceBall();
    }
});

$("#reset-ball-btn").click(function() {
    // Reset ball position
    $("#bouncing-ball").stop(true).css({ top: 0, left: '50%' });
    isBouncing = false;
});

Custom Animation Control

Create complex animations with the animate() method, controlling multiple properties simultaneously.

Example 21.4: Multi-Property Animation

Animate an element with multiple properties:

Animate Me!
// Custom animation control
$("#animate-btn").click(function() {
    const $box = $("#animated-box");
    const properties = $("#animation-properties").val();
    const animationProps = {};
    
    if (!properties || properties.length === 0) {
        alert("Please select at least one property to animate");
        return;
    }
    
    // Set animation properties based on selection
    if (properties.includes("width")) {
        animationProps.width = "200px";
    }
    if (properties.includes("height")) {
        animationProps.height = "200px";
    }
    if (properties.includes("opacity")) {
        animationProps.opacity = "0.5";
    }
    if (properties.includes("borderRadius")) {
        animationProps.borderRadius = "50%";
    }
    if (properties.includes("rotate")) {
        // For rotation we need to use CSS transform
        $box.css("transform", "rotate(0deg)");
        animationProps.transform = "rotate(360deg)";
    }
    if (properties.includes("backgroundColor")) {
        animationProps.backgroundColor = "#ff5722";
    }
    
    // Animate with options
    $box.animate(animationProps, {
        duration: 1000,
        easing: "swing",
        complete: function() {
            console.log("Animation complete!");
        }
    });
});

$("#reset-btn").click(function() {
    $("#animated-box").stop(true).css({
        width: "100px",
        height: "100px",
        opacity: "1",
        borderRadius: "8px",
        backgroundColor: "#673ab7",
        transform: "rotate(0deg)"
    });
});

Best Practices

Follow these guidelines when creating animations with jQuery:

  • Use CSS transitions when possible - For simple animations, CSS is more performant
  • Limit simultaneous animations - Too many animations can cause performance issues
  • Use easing functions - Create more natural movements with appropriate easing
  • Stop animations before starting new ones - Prevent animation queue buildup with stop()
  • Consider accessibility - Provide options to reduce motion for users with vestibular disorders
  • Use hardware acceleration - Animate properties like transform and opacity for better performance
// Best practices for jQuery animations

// 1. Stop previous animations before starting new ones
$("#element").stop().animate({...});

// 2. Use CSS transforms for better performance
$("#element").animate({
    transform: "translateX(200px) rotate(45deg)"
}, 1000);

// 3. Chain animations for sequenced effects
$("#element")
    .fadeOut(500)
    .delay(300)
    .fadeIn(500)
    .animate({left: "+=100px"}, 800);

// 4. Use easing functions for natural motion
$("#element").animate({
    left: "200px"
}, {
    duration: 1000,
    easing: "easeOutBounce"
});

// 5. Provide reduced motion option
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
    // Skip animations or use simpler transitions
    $("#element").css({left: "200px"});
} else {
    $("#element").animate({left: "200px"}, 1000);
}