DEV Community

megharrison92
megharrison92

Posted on

How to Create a Basic Carousel using JavaScript, HTML, and CSS

To create a dynamic carousel that shows images or information that rotates across the screen by using a combination of JavaScript, HTML, and CSS to format and style.

HTML

One of the first things to do, is create basic HTML structure in the project file- index.html. In the body element create a

tag and in it add all of the information that will be displayed within the carousel. Each element should have a unique identifier, either id or class. This will be used to grab the information for DOM manipulation and to style it within the style sheet.

JavaScript

Switching to the index.js file to work in, this is where the data will be declared and appended to the DOM. If information is from an API, remember to fetch the data and use the forEach() method to iterate through the array. Then declare variables in order to access the information that was fetched, change any text content or image source, and append all information to the DOM. For the carousel to work define a function that will handle the transition between the slides.

// Initialize carousel
      const carouselItems = Array.from(carousel.getElementsByClassName('carousel-item'));
      let currentIndex = 0;
      carouselItems[currentIndex].classList.add('active');

      // Function to show the next carousel item
      function showNextItem() {
        carouselItems[currentIndex].classList.remove('active');
        currentIndex = (currentIndex + 1) % carouselItems.length;
        carouselItems[currentIndex].classList.add('active');
      }

      // Set interval to automatically show the next item every 5 seconds
      setInterval(showNextItem, 5000);
    })
Enter fullscreen mode Exit fullscreen mode

CSS

Styling the carousel is what really brings it together. Here is an example of css being used-

.carousel {
  width: 100%;
  overflow: hidden;
  position: relative;
}

.carousel-item {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transition: opacity 0.5s ease;
}

.carousel-item.active {
  opacity: 1;
}

.info {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
  padding: 10px;
  font-size: 16px;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)