Build a Simple JavaScript Carousel
Published: 2023-06-05 06:39:59

Hello Coder! Welcome to the Codewithrandom blog. In this article, We use JavaScript To Build a **[Carousel Slider](https://www.codewithrandom.com/2023/02/12/simple-javascript-carousel-how-to-create-a-carousel-using-css-js/)**. The Javascript Carousel Slider's fundamental structure and styling are also created using HTML and CSS. The result of our Javascript Carousel Slider is seen here.

Before we start with today's topic let us see what exactly is Carousel Slider.

**What is the JavaScript Carousel?**

A horizontally aligned set of cards called a “card slider” can be slid to reveal other cards that are hidden. Any content is permissible on the card. such as blog cards, e-commerce product cards, profile cards, and so forth.

Advantages of Carousel:

A carousel is quite helpful when someone wants to highlight a new product or an offer, too by occupying lesser space and without making the page look jammed.

## Step 1: Carousel HTML Code

First, Let's Take a look at HTML Code.
```
 <!DOCTYPE html>  
 <html>  
   <head>  
     <title>  
       Carousel-Slider  
     </title>  
     <link href="/styles.css" type="text/css" rel="stylesheet">   
   </head>  
   <body>  
     <h1>Gear 4th Luffy</h1>  
     <div class="carousel">  
       <div class="carouselContainer">  
         <img class="slides" id="lastslide" src="/assets/3.jpg" alt="">  
         <img class="slides" src="/assets/1.jpg" alt="">  
         <img class="slides" src="/assets/2.jpg" alt="">  
         <img class="slides" src="/assets/3.jpg" alt="">  
         <img class="slides" id="firstslide" src="/assets/1.jpg" alt="">          
       </div>  
     </div>  
     <button class="button" id="prev">PREV</button>  
     <button class="button" id="next">NEXT</button>  
     <script src="/app.js"></script>  
   </body>  
 </html> 
```
In the above HTML code we have made 2 div tags;
The first div tag with class " carousel " will hold all the elements of the Carousel.

The second tag with class " carouselContainer " will hold the Images for our slides.
Below the second div tag, there are two buttons declared for the next and previous navigation of the slide.

## Step 2: Carousel CSS Code

Now let's take a look at CSS for our HTML Code
We will be going over only the essential and basic CSS today for the Carousel.
```
 *{  
   margin: 0px;  
   padding: 0px;  
   box-sizing: border-box;  
   background-color: indigo;  
 }  
 h1{  
   text-align: center;  
   color: white;  
 }  
 .carousel{  
   width:50%;  
   margin: auto;  
   overflow: hidden;  
 }  
 .carouselContainer{  
   display: flex;  
 }  
 .slides{  
   width: 100%;  
   height:390px;  
 }  
 .button{  
   position: relative;  
   transition: 0.1s ease-in;  
 }  
 #next{  
   position: absolute;  
   background-color: white;  
   opacity: 0.5;  
   top: 25%;  
   right: 25%;  
   width: 5%;  
   height: 20%;  
   z-index: 5;  
 }  
 #next:hover{  
   opacity: 0.2;  
 }  
 #prev{position: absolute;  
   background-color: white;  
   opacity: 0.5;  
   top: 25%;  
   left: 25%;  
   width: 5%;  
   height: 20%;  
   z-index: 5;  
 }  
 #prev:hover{  
   opacity: 0.2;  
 }  
```
**Step1:** First, we'll change the margin and padding to "zero" using the universal selector (*), the box-sizing property's box sizing to "border-box," and the background colour to "indigo."

Using the tag selector (h1)  we will add a text-align property we will align the heading to the center and the font-color of our heading is set to the white.
```
* {
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
    background-color: indigo;
}

h1 {
    text-align: center;
    color: white;
}
```
**Step2:** Now using the class selector (carousel)  we will set the width as 50%  and the margin is set to "auto"and using the oveflow property we will set the overflow content to "hidden"

The display property of the carousel container is set to "flex".The slides we will set the width as 100% and height as 390px 
```
.carousel {
    width: 50%;
    margin: auto;
    overflow: hidden;
}

.carouselContainer {
    display: flex;
}

.slides {
    width: 100%;
    height: 390px;
}

.button {
    position: relative;
    transition: 0.1s ease-in;
}
```
**Step3:** We will now style the following button using the id selector. We'll choose "absolute," "white," and 0.5 for the backdrop colour and opacity settings. Our slider buttons will also get the hover property.
```
#next {
    position: absolute;
    background-color: white;
    opacity: 0.5;
    top: 25%;
    right: 25%;
    width: 5%;
    height: 20%;
    z-index: 5;
}

#next:hover {
    opacity: 0.2;
}

#prev {
    position: absolute;
    background-color: white;
    opacity: 0.5;
    top: 25%;
    left: 25%;
    width: 5%;
    height: 20%;
    z-index: 5;
}

#prev:hover {
    opacity: 0.2;
}
```
## Step 3: Carousel Javascript Code

Now let's bring life to our Carousel With some JavaScript, It is the most crucial part of the code as this is exactly where we will bring all the pieces together and make them work.
```
 const carouselContainer = document.querySelector(".carouselContainer");  
 const slides = document.querySelectorAll('.slides');  
 const next = document.querySelector('#next');  
 const prev = document.querySelector('#prev');  
 let counter = 1 ;  
 const size = slides[0].clientWidth;  
 carouselContainer.style.transform = 'translateX(' + (-size * counter ) + 'px';  
 next.addEventListener('click',()=>{  
   if (counter>=slides.length)return;  
   carouselContainer.style.transition = 'transform 0.4s ease-in-out';  
   counter++;  
   carouselContainer.style.transform = 'translateX(' + (-size * counter ) + 'px';  
 });  
 prev.addEventListener('click',()=>{  
   if (counter<=0)return;  
   carouselContainer.style.transition = 'transform 0.4s ease-in-out';  
   counter--;  
   carouselContainer.style.transform = 'translateX(' + (-size * counter ) + 'px';  
 });  
 carouselContainer.addEventListener('transitionend',()=>{  
   console.log(slides[counter]);  
   if(slides[counter].id ==='lastslide'){  
   carouselContainer.style.transition = 'none';  
   counter = slides.length - 2;      
   carouselContainer.style.transform = 'translateX(' + (-size * counter ) + 'px';  
   }  
 });  
 carouselContainer.addEventListener('transitionend',()=>{  
   console.log(slides[counter]);  
   if(slides[counter].id ==='firstslide'){  
   carouselContainer.style.transition = 'none';  
   counter = slides.length - counter;      
   carouselContainer.style.transform = 'translateX(' + (-size * counter ) + 'px';  
   }  
 });  
```
Inside our javascript first of all we will select the html elements using the document.queryselector method .Then we will create a counter variable set its value as "1'. Now using the AddEventListener method we will create a click event as the user click on the event we will add an ease-in-out animiation and we will transalte to different image.

After properly applying all the code you'll Successfully create your very own Carousel.

**Conclusion** 

Note: In Html Write the Script tag at the bottom of the Body tag. This Carousel Example is not Responsive to diff. screen sizes it is an example just to make you understand the concept of a carousel and how it works.

You can try this Carousel At this Link: **[Carousel-Slider](https://www.codewithrandom.com/2023/02/12/simple-javascript-carousel-how-to-create-a-carousel-using-css-js/)**.
And the Source Code is available on my Github with all the assets: Carousel-Slider-Repo.

Leave a comment below and let us know if you have any queries.

Thank you for visiting our blog today. Please Check out our other posts.

Written by: OmBandiwan