DEV Community

Cover image for Image Carousel using JavaScript, HTML, CSS
Pradhyumn Sharma
Pradhyumn Sharma

Posted on

Image Carousel using JavaScript, HTML, CSS

Hey there!!

We all have seen carousels on many websites. And you too might have used in your web projects with the help of some framework like Bootstrap.

But today we will implement it on our own using HTML, CSS and JavaScript. And also it could be asked to you in some machine coding interview round.

Before we dive into the coding part let’s understand the structure of a carousel.

  1. We have main div, we can call it as the container (div#container) with some width and height.

  2. We have let’s say 4 div inside the main div that contains our images (div.image__container).

  3. Every inner div contains an image taking full width and height of the parent and also object-fit : cover property, so our every image covers the whole div.

  4. Now, the main div would be having display : flex property so that our inner divs are in a row but we need to show one image at a time so we need to apply overflow : hidden property too.

  5. We need two buttons, one to move to the next image and one to get back to the previous one.

After these 5steps our output would be like this.

Coding wallpaper

  • Now here’s one thing to note, by default flex property has flex-shrink : 1 set to the children, that’s why our images are being shrunk, but for our use case we want the div to take full width of the main container. In order to achieve that we need to put flex-shrink : 0 for inner divs.

And after this step our output would be like this.

Coding wallpaper

Now let’s have some dive into coding!!

1. HTML

<!DOCTYPE html>
<head>
    <link href="carousel.css" rel="stylesheet" />
</head>
<body>
    <div id="carousel__container">
        <div class="img__container">
        <img class="carousel__img" src="https://i.ibb.co/K2KkmJx/florian-olivo-4hb-J-eym-Z1o-unsplash.jpg" alt="carousel-img" />
        </div>
        <div class="img__container">
            <img class="carousel__img" src="https://i.ibb.co/3Nmfpsm/jackson-sophat-t-l5-FFH8-VA-unsplash.jpg" alt="carousel-img" />
        </div>
        <div class="img__container">
            <img class="carousel__img" src="https://i.ibb.co/sVXbVdr/nathan-da-silva-k-r-Kfq-Sm4-L4-unsplash.jpg" alt="carousel-img" />
        </div>
        <div class="img__container">
        <img class="carousel__img" src="https://i.ibb.co/fMf7S4k/kobu-agency-ip-ARHax-ETRk-unsplash.jpg" alt="carousel-img" />
        </div>
        <button id="prev-btn" class="btn">P</button>
        <button id="next-btn" class="btn">N</button>
        </div>
</body>
<script src="carousel.js"></script>
</html>
Enter fullscreen mode Exit fullscreen mode

2. CSS

#carousel__container {
  position: relative;
  display: flex;
  width: 600px;
  height: 300px;
  overflow: hidden;
  border: 1px solid red;
}

.img__container {
  width: 100%;
  height: 100%;
  flex-shrink: 0;
}
.img__container > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.btn {
  position: absolute;
  top: 50%;
  border-radius: 50%;
  color: black;
  background-color: white;
  border: none;
  outline: none;
  padding: 5px 7px;
  cursor: pointer;
}
#prev-btn {
  left: 10px;
}
#next-btn {
  right: 10px;
}
Enter fullscreen mode Exit fullscreen mode

3. JavaScript : This is where all the magic happens.

This block of code is simple to understand, we are adding event listeners to our buttons so to invoke corresponding functions.

We are getting our images from the DOM and storing them in an array.

const nextBtn = document.getElementById("next-btn");
const prevBtn = document.getElementById("prev-btn");

nextBtn.addEventListener("click", showNextImage);
prevBtn.addEventListener("click", showPrevImage);

//document.getElementsByClassName return HTML collection so we are using "Array.from" method to get an iterable

const images = Array.from(document.getElementsByClassName("carousel__img"));
const totalImages = images.length;

let currentImageIndex = 0; //index of image that being display on screen
Enter fullscreen mode Exit fullscreen mode

You must have seen that in a carousel, images slide with a smooth sliding effect so to add the same effect, we are creating a function that add CSS styling to every image..

function addTransitionEffectToImages() {
  images.forEach((img) => {
    img.style.transition = "transform 0.8s ease";
  });
}
Enter fullscreen mode Exit fullscreen mode

Now let’s understand what happens when user click on the next button.

  • Firstly, we are adding the transition effect to our images so they slide smoothly giving a sliding effect.
  • In CSS, we have transform property through which we can animate a HTML element in various ways. But for our use case we want to move our inner divs in X(horizontal) direction by some specific pixels or percentage. For that we have translateX function. If we want our element to move in right direction, the value passed would be positive and vice-versa.
transform : translateX(50px); //moves elements to right by 50px
transform : translateX(-30px); //moves elements to left by 30px

transform : translateX(100%); //moves elements to right as far as its length
transform : translateX(-100%); //moves elements to left as far as its length
Enter fullscreen mode Exit fullscreen mode
  • Now, every time we click on the next button, every image would move to the left based on what position they are at currently on and update the index by 1.
  • If we are on last image we will reset our carousel using the resetCarousel() function.
function showNextImage() {
  //if we are at last image reset the carousel
  if (currentImageIndex == totalImages - 1) {
    resetCarousel();
    return;
  }

if (currentImageIndex === 0) addTransitionEffectToImages();
  //translate every image with (-100%) every time we go to next image
  images.forEach((img) => {
    img.style.transform = `translate(${(currentImageIndex + 1) * -100}%)`;
  });
  currentImageIndex++;
}
Enter fullscreen mode Exit fullscreen mode
function resetCarousel() {
  images.forEach((img) => {
    //we are setting "none" so when every image gets back to position we don't want to show sliding effect
    img.style.transition = "none";
    img.style.transform = `translate(0)`; //every image back to original position
  });
  currentImageIndex = 0;
}
Enter fullscreen mode Exit fullscreen mode

In our resetCarousel() function we are removing the transition property because every image will return to its normal position but with the sliding effect like a train goes on but we don’t want that. Removing this property will show directly the first image without any effect. You can try removing in your code and see what happens.

We are remaining with one last thing that how to make previous button work.

  • If we are on the 1st image then we simply return.
  • The logic of this part is opposite of the next button functionality. We simple translateX the images by -100% and decrement the index by 1.
function showPrevImage() {
  if (currentImageIndex === 0) return; //if we are at first image, then simply return

//reverse logic for what we did in showNextImage
  images.forEach((img) => {
    img.style.transform = `translateX(${(currentImageIndex - 1) * -100}%)`;
  });
  currentImageIndex--;
}
Enter fullscreen mode Exit fullscreen mode

Happy Coding!!

Thank you for reading…Do like and comment!!

Top comments (1)

Collapse
 
dannyengelman profile image
Danny Engelman

Make it a working JSFiddle or something, your code doesn't run after doing 5 copy/pastes into our own IDE