Create an Autoplay Carousel using HTML CSS and JavaScript (original) (raw)

Last Updated : 23 Aug, 2024

An Autoplay Carousel is a dynamic UI element that automatically cycles through a series of images or content slides, providing a visually engaging way to display information. It enhances user experience by showcasing multiple items in a limited space without manual navigation. This can be implemented using HTML, CSS, and JavaScript.

Prerequisites:

Approach

**Example: This example describes the basic implementation of the the autoplay carousel using HTML, CSS, and JavaScript.

HTML `

Autoplay Carousel
<script src="./script.js"></script>

CSS

body { display: flex; justify-content: center; align-items: center; }

.carousel { position: relative; width: 270px; height: 160px; overflow: hidden; background-color: #cdcdcd; }

.carousel-item .slide-image { width: 270px; height: 160px; background-size: cover; background-repeat: no-repeat; }

.carousel-item { position: absolute; width: 100%; height: 270px; border: none; top: 0; left: 100%; }

.carousel-item.active { left: 0; transition: all 0.3s ease-out; }

.carousel-item div { height: 100%; }

.red { background-color: red; }

.green { background-color: green; }

.yellow { background-color: yellow; }

.violet { background-color: violet; }

JavaScript

window.onload = function () { let slides = document.getElementsByClassName('carousel-item');

function addActive(slide) {
    slide.classList.add('active');
}

function removeActive(slide) {
    slide.classList.remove('active');
}

addActive(slides[0]);
setInterval(function () {
    for (let i = 0; i < slides.length; i++) {
        if (i + 1 == slides.length) {
            addActive(slides[0]);
            setTimeout(removeActive, 350, slides[i]);
            break;
        }
        if (slides[i].classList.contains('active')) {
            setTimeout(removeActive, 350, slides[i]);
            addActive(slides[i + 1]);
            break;
        }
    }
}, 1500);

};

`

**Output: