Open In App

Animated Slideshow App in HTML CSS & JavaScript

We will learn to create a slideshow of multiple images. This slideshow will transition between the images every few seconds. we will further learn to align the images, style the images, and make the animation look better.



Prerequisites

Approach

Example: This example shows the implementation of the above-explained approach.




let currentSlide = 0;
 
function showSlide(index) {
    const slides = document.querySelectorAll('.slide');
 
    slides.forEach((slide, i) => {
        slide.style.display = i === index ? 'flex' : 'none';
    });
}
 
function nextSlide() {
    currentSlide = (currentSlide + 1) % 6;
    showSlide(currentSlide);
}
 
setInterval(nextSlide, 2000);




<!DOCTYPE html>
<html>
 
<head>
    <title>GFG</title>
    <link rel="stylesheet" href="style.css" />
</head>
 
<body>
    <h1>Slide Show</h1>
    <div class="slideshow-container">
        <div class="slide fade">
            <img src=
                alt="Slide 1">
        </div>
        <div class="slide fade">
            <img src=
        </div>
        <div class="slide fade">
            <img src=      
                alt="Slide 3">
        </div>
        <div class="slide fade">
            <img src=
                alt="Slide 3">
        </div>
        <div class="slide fade">
            <img src=
        </div>
        <div class="slide fade">
            <img src=
        </div>
    </div>
    <script src="./script.js"></script>
</body>
 
</html>




body {
    padding-bottom: 20px;
    font-family: Arial, sans-serif;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
    box-sizing: border-box;
    overflow: hidden;
}
 
h1 {
    font-size: 4vw;
}
 
.slideshow-container {
    width: 60%;
    aspect-ratio: 1;
    position: relative;
    margin: auto;
    overflow: hidden;
    border-radius: 10px;
    box-shadow: 2px 2px 5px
}
 
.slide {
    display: none;
    width: 100%;
    height: 100%;
    overflow: hidden;
    justify-content: center;
    align-items: center;
 
}
 
img {
    width: 100%;
    height: 100%;
    object-fit: contains;
}
 
.fade {
    animation: fade 2s ease-in-out infinite;
}
 
@keyframes fade {
    from {
        opacity: 0.4;
    }
 
    to {
        opacity: 1;
    }
}

Output:




Article Tags :