Open In App

Automatic Image Slider using JavaScript

In this article, we will discuss how to create an automatic image slider using JavaScript. An image slider is a popular component of modern websites that allows the display of multiple images in a single location, usually in a sliding motion. With the use of JavaScript, creating an automatic image slider has become much simpler.

Preview:



Approach:

Example: The below example explains how you can use JavaScript to create an automatic image slider.




const slider = document.querySelector('.slider');
const slides = slider.querySelectorAll('li');
 
// Store the total number of images
const slideCount = slides.length;
let activeSlide = 0;
 
// To change the images dynamically every
// 5 Secs, use SetInterval() method
setInterval(() => {
  slides[activeSlide].classList.remove('active');
  activeSlide++;
  if (activeSlide === slideCount) {
    activeSlide = 0;
  }
  slides[activeSlide].classList.add('active');
}, 2000);




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width,
                   initial-scale=1.0">
    <title>Image Slider</title>
    <link rel="stylesheet"
          href="style.css">
</head>
 
<body>
    <center>
        <div class="slider">
            <ul>
                <li>
                    <img src=
                        alt="GFG Image 1">
                    <div class="caption">
                        Geeks for Geeks
                    </div>
                </li>
                <li>
                    <img src=
                        alt="GFG Image 2">
                    <div class="caption">
                        Geeks for Geeks
                    </div>
                </li>
                <li>
                    <img src=
                        alt="GFG Image 3">
                    <div class="caption">
                        Geeks for Geeks
                    </div>
                </li>
                <li>
                    <img src=
                        alt="GFG Image 4">
                    <div class="caption">
                        Geeks for Geeks
                    </div>
                </li>
            </ul>
        </div>
    </center>
 
    <script src="script.js"></script>
</body>
 
</html>




.slider {
    width: 100%;
    position: relative;
}
 
.slider ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
 
.slider li {
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0;
    transition: opacity 1s ease-in-out;
}
 
img {
    height: 400px;
    width: 400px;
}
 
.slider li.active {
    opacity: 1;
}
 
.slider .caption {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    color: #fff;
    font-size: 18px;
    padding: 10px;
    text-align: center;
}

Output:




Article Tags :