Open In App

Create an Autoplay Carousel using HTML CSS and JavaScript

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • HTML Structure: The HTML structure consists of a .carousel container holding .carousel-item elements, each containing a background image.
  • CSS – Carousel Container: The .carousel is styled with a fixed size and overflow: hidden, positioning child items for sliding functionality.
  • CSS – Slide Positioning: The .carousel-item elements are absolutely positioned outside the view (left: 100%) and slide into view when activated.
  • CSS – Active Slide Transition: The .carousel-item.active moves into view (left: 0) with a smooth 0.3s transition, enabling seamless slide transitions.
  • JavaScript – Initial Slide Activation: The first slide is initialized as active using addActive(slides[0]), making it visible when the page initially loads.
  • JavaScript – Automatic Slide Cycling: The setInterval function cycles through slides every 1.5 seconds, removing active from the current slide and activating the next.

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

HTML
<!DOCTYPE html>
<html>

<head>
    <title>Autoplay Carousel</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="carousel">
        <div class="carousel-item">
            <div class="slide-image"
                style="background-image: 
url('https://media.geeksforgeeks.org/img-practice/banner/mern-full-stack-development-classroom-thumbnail.png?v=19625');">
            </div>
        </div>
        <div class="carousel-item">
            <div class="slide-image"
                style="background-image: 
url('https://media.geeksforgeeks.org/img-practice/banner/dsa-to-development-coding-guide-thumbnail.png?v=19625');">
            </div>
        </div>
        <div class="carousel-item">
            <div class="slide-image"
                style="background-image: 
url('https://media.geeksforgeeks.org/img-practice/banner/geeks-classes-live-thumbnail.png?v=19625');">
            </div>
        </div>
        <div class="carousel-item">
            <div class="slide-image"
                style="background-image: 
url('https://media.geeksforgeeks.org/img-practice/banner/gate-crash-course-2024-thumbnail.png?v=19625');">
            </div>
        </div>
    </div>

    <script src="./script.js"></script>
</body>

</html>
CSS JavaScript

Output:



Next Article

Similar Reads