Image Carousel With Pure JavaScript


An Image Slider that comprises several images displayed on a web application is called "Slide Show" and "Carousels". It permits you to show multiple images, videos, or graphics on a web application. Also, adding an Image Slider to a website can fascinate the users and capture their attention.

An image carousel, also known as a slideshow or a rotating banner, is a way to display multiple images in a looping sequence. The images can be navigated through using buttons or indicators, and can be set to automatically rotate at a specified interval.

In JavaScript, you can create an image carousel by creating a container element, such as a <div>, and then using the document.createElement() method to create new <img> elements for each image. You can then use JavaScript to handle the logic for displaying the images, such as switching between images when the user clicks on a button or an indicator, or automatically rotating through the images at a specified interval.

It is also important to note that the performance of carousel with a large number of images can have an impact on the user experience. To create a more complex and functional carousel, you can use additional JavaScript and CSS to handle the navigation, styling, and other features.

There are also many libraries available that can help you create an image carousel in JavaScript, such as Slick, Owl Carousel and many more. These libraries are pre-built and easy to use, but you may have limited control over the design and functionality of the carousel.

This write-up will teach the procedure of creating an image slider in JavaScript. So, let’s start!

Source Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Slider</title>
  <link rel="stylesheet" href="css/style.css">
  <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>

</head>
<body>
  <div class="slider">

    <div class="slider-item active">
      <img src="images/1.jpg" alt="Slider-1">
    </div>
    <div class="slider-item">
      <img src="images/2.jpg" alt="Slider-2">
    </div>
    <div class="slider-item">
      <img src="images/3.jpg" alt="Slider-3">
    </div>
    <div class="slider-item">
      <img src="images/4.jpg" alt="Slider-4">
    </div>
    <div class="slider-item">
      <img src="images/5.jpg" alt="Slider-5">
    </div>

    <div class="slider-btns">
      <button id="btn-prev">
        <ion-icon name="chevron-back-outline"></ion-icon>
      </button>
      <button id="btn-next">
        <ion-icon name="chevron-forward-outline"></ion-icon>
      </button>
    </div>

    <div class="dots">
      
    </div>

  </div>
  <script src="js/script.js"></script>
</body>
</html>

css/style.css

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap');

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}

body{
  width: 100vw;
  height: 100vh;
  display: grid;
  place-items: center;
}


.slider{
  max-width: 800px;
  height: 400px;
  position: relative;
  user-select: none;
}

.silder img{
  width: 100%;
  height: auto;
}

.slider-item,
.hidden
{
display: none;
}

.active{
  display: block;
  animation: fadeAnimation 0.5s;
}
.slider-btns{
  position: absolute;
  top:50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between; 
  visibility: hidden;
}
.slider-btns button{
  font-size: 30px;
  font-weight: 500;
  background-color:rgba(0,0,0,0.5);
  border:none;
  color:white;
  width: 30px;
  height: 30px;
  line-height: 30px;
  cursor: pointer;
}

.slider:hover .slider-btns{
visibility: visible;
}

@keyframes fadeAnimation {
  0%{
    opacity: 0;
  }
  100%{
    opacity: 1;
    transition: opacity linear;
  }
}

.dots{
  background-color: rgba(0,0,0,0.5);
  width: 100%;
  height: 15px;
  position: absolute;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  gap:10px;
}

.dot{
  width: 20px;
  height: 3px;
  background-color: rgba(241,241,241,0.2);
  cursor: pointer;
}

.dot-active{
  background-color:#fff;
}

This JavaScript code creates an image carousel by using the document.querySelectorAll() method to select all elements with the class "slider-item" and store them in the sliders variable. The totalSlider variable is used to store the total number of images in the carousel.

The code also creates two variables, btnPrev and btnNext, which select the elements with the ids "btn-prev" and "btn-next" respectively. These elements are used as buttons to navigate between the images in the carousel. The addEventListener() method is used to attach click event handlers to these buttons, which call the PrevSlide() and NextSlide() functions when clicked.

The PrevSlide() and NextSlide() functions are used to navigate between the images in the carousel. The PrevSlide() function decreases the value of the slidePosition variable by 1, or sets it to the last image if it is currently at the first image. The NextSlide() function increases the value of the slidePosition variable by 1, or sets it to the first image if it is currently at the last image.

The updatePosition() function is called after each button click, it loops through all the sliders elements and removes the class "active" and add 'hidden' class, then it adds the class "active" to the current slide, determined by the value of the slidePosition variable.

The code also creates dots for each slide and append them to an element with class 'dots' and attach click event to each dot, when clicked it sets slide position to the index of dot, and call the updatePosition() function to update the active slide.

Additionally, the code uses setInterval() function to automatically navigate through the images in the carousel every 5 seconds. This function increments the value of the slidePosition variable and calls the updatePosition() function to update the active slide.

js/script.js

let slidePosition=0;
const sliders=document.querySelectorAll('.slider-item');
const totalSlider=sliders.length;
const btnPrev=document.querySelector('#btn-prev');
const btnNext=document.querySelector('#btn-next');


btnPrev.addEventListener('click',function(){
  PrevSlide();
});
btnNext.addEventListener('click',function(){
  NextSlide();
});

function updatePosition(){
  sliders.forEach(slide=>{
    slide.classList.remove('active');
    slide.classList.add('hidden');
  });

  sliders[slidePosition].classList.add('active');

  dots.forEach(dot=>{
    dot.classList.remove('dot-active');
  });

  dots[slidePosition].classList.add('dot-active');
}

function PrevSlide(){
  if(slidePosition==0){
    slidePosition=totalSlider-1;
  }else{
    slidePosition--;
  }
  updatePosition();
}
function NextSlide(){
  if(slidePosition==totalSlider-1){
    slidePosition=0;
  }else{
    slidePosition++;
  }
  updatePosition();
}


const dotContainer=document.querySelector('.dots');
sliders.forEach(slide=>{
 const dot=document.createElement('div');
 dot.classList.add('dot');
 dotContainer.appendChild(dot);
});

const dots=document.querySelectorAll('.dot');
dots[slidePosition].classList.add('dot-active');


dots.forEach((dot,index)=>{
  dot.addEventListener('click',function(){
    slidePosition=index;
    updatePosition();
  });
});


setInterval(()=>{
  if(slidePosition==totalSlider-1){
    slidePosition=0;
  }else{
    slidePosition++;
  }
  updatePosition();
},5000);

Output

Image Carousel

Live Preview


List of Programs


JS Practical Questions & Answers


JS Practical Project