Skip to content

How to Create Auto Carousel in JavaScript

Last updated on February 28, 2020

In this post, I thought of sharing one challenge which I took to create auto carousel in javascript.

I hope some of us might have experienced this at least once in a while including myself. Then later I planned to create one for myself.

Introduction

To make use of the auto carousel feature in our project, we always depend on 3rd party tools like bootstrap. Even we can also create on our own. But we need to know what’s all needed in order to build an auto carousel feature.

Instead of replicating entirely from the bootstrap framework, we can build minimal feature of auto carousel component

Idea

The idea is totally simple. 1. Have carousel buttons at the very bottom and slides at the top position within the container element.

2. By clicking any carousel, we will get the respective slide. One more fancy stuff here is that when we change to mobile viewport, we put the slides into auto mode but hidden carousel.

3. In addition to having default background color of carousel, we need to have background color change on selection of carousel.

4. The carousel count is based on number of slides.

Code

// index.html
<div class="carousel">
  <div class="carousel- item"></div>
</div>
//styles.css
.carousel {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 5%;
  padding: 0 10px;
}

.carousel > .carousel-item {
  width: 15px;
  height:15px;
  background-color: var(--default-carousel-bg-color);
  border-radius: 50%;
  margin-left: 5px;
}

.carousel-item:hover {
  cursor: pointer;
}

.selected-carousel {
  background-color: var(--selected-carousel-bg-color);
}

We toggle the . selected-carousel css class to the carousel-item based on the selection of the carousel.

I’ve drawn this component in JavaScript. If possible you can also try at your end.

References

Published inCSSFrameworksJavaScriptReact