Episode 23 of 24

Fading Animation Example

Build a practical fading image slideshow combining fade effects and timers.

Let's put our animation knowledge together and build a real-world example — an automatic image slideshow with fade transitions.

HTML Structure

<div class="slideshow">
    <div class="slide active">
        <h2>Slide 1</h2>
        <p>Welcome to our amazing slideshow</p>
    </div>
    <div class="slide">
        <h2>Slide 2</h2>
        <p>Built with jQuery animations</p>
    </div>
    <div class="slide">
        <h2>Slide 3</h2>
        <p>Simple and elegant</p>
    </div>
    <button class="prev">← Prev</button>
    <button class="next">Next →</button>
</div>

CSS

.slideshow {
    position: relative;
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    overflow: hidden;
}

.slide {
    display: none;
    padding: 4rem 2rem;
    text-align: center;
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white;
    border-radius: 12px;
}

.slide.active { display: block; }

jQuery Code

$(function() {
    let current = 0;
    let $slides = $(".slide");
    let total = $slides.length;

    function showSlide(index) {
        $slides.eq(current).fadeOut(400, function() {
            current = (index + total) % total;
            $slides.eq(current).fadeIn(400);
        });
    }

    $(".next").click(function() { showSlide(current + 1); });
    $(".prev").click(function() { showSlide(current - 1); });

    // Auto-play every 4 seconds
    let autoPlay = setInterval(function() {
        showSlide(current + 1);
    }, 4000);

    // Pause on hover
    $(".slideshow").hover(
        function() { clearInterval(autoPlay); },
        function() {
            autoPlay = setInterval(function() {
                showSlide(current + 1);
            }, 4000);
        }
    );
});

This pattern can be extended with dot indicators, thumbnail navigation, or swipe support.