JavaScript Automatic Carousel Example

Go back to JavaScript Index

In this tutorial, we will be creating an automatic carousel, like the one shown here:

The Carousel

Credits: unsplash-logoJordan Arnold and unsplash-logoVincent van Zalinge


The HTML in the example consist of a container that holds the images.


<img src="img/jordan-arnold-1513926-unsplash.jpg" alt="Nature image by Jordan Arnold on Unsplash" class="slide">
<img src="img/vincent-van-zalinge-1405470-unsplash.jpg" alt="Fawn image by Vincent van Zalinge on Unsplash" class="slide">
<img src="img/vincent-van-zalinge-44086-unsplash.jpg" alt="Butterfly image by Vincent van Zalinge on Unsplash" class="slide">
<img src="img/vincent-van-zalinge-1393808-unsplash.jpg" alt="Hare image by Vincent van Zalinge on Unsplash" class="slide">
1.0 | The HTML

Each image (or slide) has the class name "slide", and they are all children of the container (div).


Obviously the example uses some of the style instructions of this site, but in this tutorial I will focus on the style instructions necessary to create the actual carousel:


.slide {
display: none;
1.1 | The CSS

The CSS is used to hide all of the images or slides in our carousel.

The JavaScript

The JavaScript used to create the example looks like this:


let index = 0;

const carousel = () => {
let slides = Array.from(document.getElementsByClassName("slide"));
slides.forEach(slide => = "none");
if (index > slides.length) {
index = 1
slides[index-1].style.display = "block";

setTimeout(carousel, 3000); // Change image every 3 seconds

1.2 | The JS

The index variable is used to store the index number.

A function called carousel is declared using the const keyword and the arrow syntax. The function does a number of things:

  • It creates an array of all the HTML elements with class name "slide" using the Array.from() method and the DOM method document.getElementsByClassName()
  • It iterates through the slides array and sets the display property of each slide to display none. This is done in order to hide the previous image before the next one is to show.
  • It increments the value of index by 1.
  • It looks at the value of the index variable and compares it to the number of elements in the slides array. If the value of the index variable is greater than the number of slides in the array, it resets the number to 1
  • It then graps a specific element from the array (the one that has the value of the index variable - 1) and changes the value of the display property to "block", unhiding the element.
  • A timer is then set that calls the carousel function every 3 seconds (3000 milliseconds), making the images change as the value of the index variable increases or is reset.

Outside the function, the function is called once.