{}const=>[]async()letfn</>var
WebJSPractice

How to Create a Slider in Pure JavaScript: A Step-by-Step Guide

Learn how to create a slider in pure JavaScript without using libraries. Step-by-step guide with examples and explanation of key steps.

К

Kodik

Author

4 min read

Hi! 👋 Today we will analyze how to create a simple but functional image slider in pure JavaScript. We won't use third-party libraries so that you can better understand how each slider element works and how it can be improved.

You can view the finished slider here: https://coursme.github.io/02-slider-js/

Step 1. Prepare the HTML structure

First of all, we need to create an HTML structure for the slider. We will use the <div> element to wrap the slides and several images that will be switched.

HTML template:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Simple Image Slider</title>
  <style>
    .slider {
      width: 500px;
      height: 300px;
      overflow: hidden;
      position: relative;
    }
    
    .slides {
      display: flex;
      transition: transform 0.5s ease-in-out;
    }
    
    .slide {
      min-width: 100%;
      box-sizing: border-box;
    }
    
    img {
      width: 100%;
      height: 100%;
    }
    
    .controls {
      position: absolute;
      top: 50%;
      width: 100%;
      display: flex;
      justify-content: space-between;
      transform: translateY(-50%);
    }
    
    .control {
      background-color: rgba(0, 0, 0, 0.5);
      color: white;
      border: none;
      font-size: 18px;
      cursor: pointer;
      padding: 10px;
    }
  </style>
</head>
<body>
  <h1>Слайдер изображений</h1>

  <div class="slider">
    <div class="slides">
        <div class="slide"><img src="https://placehold.co/500x300?text=Slide+1" alt="Slide 1"></div>
        <div class="slide"><img src="https://placehold.co/500x300?text=Slide+2" alt="Slide 2"></div>
        <div class="slide"><img src="https://placehold.co/500x300?text=Slide+3" alt="Slide 3"></div>
    <div class="controls">
      <button class="control" id="prevBtn">&lt;</button>
      <button class="control" id="nextBtn">&gt;</button>
    </div>
  </div>

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

📋 Explanation:

  • .slider: A slide wrapper that sets fixed dimensions and hides everything that goes beyond the borders (overflow: hidden).

  • .slides: A container for all slides that will move left or right to change images.

  • .slide: Each individual slide. We set its width to 100% so that it occupies the entire visible area.

  • Control buttons: These are the "forward" and "back" buttons that will switch slides.


Step 2. Adding logic for switching slides

Now let's move on to the main logic — switching slides when you click on the buttons. We need to track the current slide and move the .slides container using the transform CSS property.

Implementation in script.js:

const slides = document.querySelector('.slides');
const slide = document.querySelectorAll('.slide');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');

let currentIndex = 0;
const totalSlides = slide.length;

function updateSliderPosition() {
  slides.style.transform = `translateX(-${currentIndex * 100}%)`;
}

nextBtn.addEventListener('click', () => {
  if (currentIndex < totalSlides - 1) {
    currentIndex++;
  } else {
    currentIndex = 0; // Return to the first slide
  }
  updateSliderPosition();
});

prevBtn.addEventListener('click', () => {
  if (currentIndex > 0) {
    currentIndex--;
  } else {
    currentIndex = totalSlides - 1; // Go to the last slide
  }
  updateSliderPosition();
});

🔨 How it works:

  • translateX(): We use this property to shift the slide container to the left or right depending on the index of the current slide.

  • Button logic: Each button increases or decreases the slide index, after which the updateSliderPosition() function is called, which updates the container position.


Step 3. Add auto-switching of slides

To make our slider more convenient, we will add the function of auto-switching slides at certain intervals. This will create the effect of an endless gallery.

Let's add auto-switching:

let autoSlideInterval = setInterval(() => {
  if (currentIndex < totalSlides - 1) {
    currentIndex++;
  } else {
    currentIndex = 0;
  }
  updateSliderPosition();
}, 3000); // Slide change every 3 seconds

// Stop auto-switching when interacting with buttons
nextBtn.addEventListener('click', () => {
  clearInterval(autoSlideInterval);
  autoSlideInterval = setInterval(() => {
    if (currentIndex < totalSlides - 1) {
      currentIndex++;
    } else {
      currentIndex = 0;
    }
    updateSliderPosition();
  }, 3000);
});

prevBtn.addEventListener('click', () => {
  clearInterval(autoSlideInterval);
  autoSlideInterval = setInterval(() => {
    if (currentIndex < totalSlides - 1) {
      currentIndex++;
    } else {
      currentIndex = 0;
    }
    updateSliderPosition();
  }, 3000);
});

🕒 Description:

  • We use the setInterval() function to automatically switch the slide every 3 seconds.

  • Interaction with the buttons (forward/back) pauses the auto-switching, but then starts it again so that the slider continues to work automatically.


Step 4. Completion and testing

Now your slider is fully functional! You can switch slides manually using the buttons or let the slider automatically change images every few seconds.


Conclusion

Creating a slider in pure JavaScript is a great way to practice DOM manipulation and CSS. Such a slider can be easily expanded by adding, for example, animations, fading effects, or navigation using indicator points. 🚀

If you have any questions or you want to add new features to the slider, I'm always happy to help! 😄

Repository with final code: https://github.com/Coursme/02-slider-js

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card