OfferGenie
All Questions

How do I create a carousel using vanilla JavaScript?

AmazonTechnicalDifficulty: Medium
Share on

Ready to answer it out loud?

Run a mock interview on this exact question and get instant AI feedback.

Practice this question

Question Explain

How can I build a fully functional image carousel using only vanilla JavaScript, including detailed instructions on setting up the HTML structure, styling with CSS, and implementing the JavaScript logic for navigation and slide transitions?

Answer Example

Creating a fully functional image carousel using vanilla JavaScript involves setting up an HTML structure, applying CSS styles for appearance, and implementing JavaScript for navigation and transitions. Below is a step-by-step guide to help you build an image carousel:

Step 1: HTML Structure

Start by setting up the basic HTML structure for your carousel. Here's a simple example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Carousel</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="carousel">
        <div class="carousel-inner">
            <img src="image1.jpg" alt="Image 1" class="carousel-item">
            <img src="image2.jpg" alt="Image 2" class="carousel-item">
            <img src="image3.jpg" alt="Image 3" class="carousel-item">
        </div>
        <button class="carousel-control prev">Prev</button>
        <button class="carousel-control next">Next</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 2: CSS Styling

Next, apply CSS to style the carousel. You'll focus on positioning, transitions, and visibility of the images:

.carousel {
    position: relative;
    width: 600px;
    overflow: hidden;
    margin: auto;
}

.carousel-inner {
    display: flex;
    transition: transform 0.5s ease;
}

.carousel-item {
    min-width: 100%;
    max-width: 100%;
    display: block;
}

.carousel-control {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    border: none;
    padding: 10px;
    cursor: pointer;
}

.prev {
    left: 10px;
}

.next {
    right: 10px;
}

button:focus {
    outline: none;
}

Step 3: JavaScript Logic

Finally, implement the JavaScript logic for navigating through the carousel:

document.addEventListener('DOMContentLoaded', function() {
    const carousel = document.querySelector('.carousel-inner');
    const items = document.querySelectorAll('.carousel-item');
    const totalItems = items.length;
    let currentIndex = 0;

    document.querySelector('.next').addEventListener('click', function() {
        currentIndex = (currentIndex + 1) % totalItems;
        updateCarousel();
    });

    document.querySelector('.prev').addEventListener('click', function() {
        currentIndex = (currentIndex - 1 + totalItems) % totalItems;
        updateCarousel();
    });

    function updateCarousel() {
        const offset = -currentIndex * 100;
        carousel.style.transform = `translateX(${offset}%)`;
    }

    // Optionally, you can add auto-rotate functionality
    // setInterval(function() {
    //     currentIndex = (currentIndex + 1) % totalItems;
    //     updateCarousel();
    // }, 3000);
});

Explanation

  • HTML: Structure consists of a container (.carousel) with a .carousel-inner that holds each image (.carousel-item). Navigation buttons are outside the images for prev/next functionality.

  • CSS: Uses flex for the linear layout of items inside .carousel-inner. The images have a min-width of 100% to ensure consistency in display, and transitions are smoothly animated.

  • JavaScript: Attaches event listeners to buttons to change the currentIndex, updating the transform CSS property of the .carousel-inner to show the relevant picture. The modulus operator % allows for continuous looping through images.

This setup provides a basic but fully functioning image carousel. You can extend this with additional features like auto-slide or paginated navigation as needed.