# Building an Image Slider with Vanilla JavaScript

An image slider looks like it needs a library. It doesn't. The core idea fits in one sentence: **keep all the images on the page, and show only one at a time.**

This post walks through a small slider with four images, a Prev button and a Next button. It loops, so pressing Next on the last image brings you back to the first.

## The idea

Think of a stack of photographs where only the top one is visible. In the browser, a CSS class called `active` decides which photo that is. JavaScript never creates or loads anything on a click. It only moves the class from one slide to another.

Each part has one job:

- **HTML** holds the slides and buttons.
- **CSS** decides what is visible.
- **JavaScript** decides which slide is active.

## The HTML

```html
<div class="image-slider">
  <div class="image-items">
    <div class="item active">
      <img src="image1.jpg" alt="Image 1">
    </div>
    <div class="item">
      <img src="image2.jpg" alt="Image 2">
    </div>
    <div class="item">
      <img src="image3.jpg" alt="Image 3">
    </div>
    <div class="item">
      <img src="image4.jpg" alt="Image 4">
    </div>
  </div>
  <div class="controls">
    <button id="prev">Prev</button>
    <button id="next">Next</button>
  </div>
</div>
```

The first slide starts with `active`, so there is something to see before any script runs. The buttons sit outside `.image-items`, which means that container's children are the slides and nothing else. The JavaScript relies on this.

## The CSS that does the switching

```css
.image-items .item {
  display: none;
}

.image-items .item.active {
  display: block;
}
```

These two rules are the heart of the slider. Every slide is hidden, except the one that also has `active`. The second selector is more specific, so it wins.

The rest is presentation:

```css
.image-slider {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: auto;
  width: 500px;
  height: 500px;
}

.image-items {
  border: 8px solid var(--yellow);
  border-radius: 4px;
}

.image-items .item img {
  max-width: 100%;
  display: block;
}
```

`--yellow` is a colour variable from the project's shared stylesheet. `display: block` on the image removes the small gap browsers leave under inline images.

## The JavaScript

### 1\. Collect the elements

```js
const slides = document.querySelector(".image-items").children;
const prevSlide = document.querySelector("#prev");
const nextSlide = document.querySelector("#next");
const totalSlides = slides.length;

let currentIndex = 0;
```

`slides` is the list of slide elements. `currentIndex` is the only thing the slider has to remember. Because `totalSlides` is read from the page, adding a fifth image needs no change to the script.

### 2\. Listen for clicks

```js
nextSlide.addEventListener("click", () => {
  imageSlide('next');
});
prevSlide.addEventListener("click", () => {
  imageSlide('prev');
});
```

Both buttons call the same function and pass a direction.

### 3\. Move the active class

```js
const imageSlide = (direction) => {
  slides[currentIndex].classList.remove("active");

  if (direction === 'next') {
    currentIndex++;
    if (currentIndex === totalSlides) currentIndex = 0;
    slides[currentIndex].classList.add("active");
  }

  if (direction === 'prev') {
    if (currentIndex === 0) currentIndex = totalSlides;
    currentIndex--;
    slides[currentIndex].classList.add("active");
  }
}
```

The pattern is: hide the current slide, work out the new index, show the new slide.

## How the looping works

Array-like lists start at zero, so four slides have indexes 0 to 3.

- **Next:** add one. If the result is 4, there is no such slide, so go back to 0.
- **Prev:** if we are at 0, first jump to 4, then subtract one. That lands on 3, the last slide.

You can also write both cases with the remainder operator:

```js
const step = direction === 'next' ? 1 : -1;
currentIndex = (currentIndex + step + totalSlides) % totalSlides;
```

Adding `totalSlides` keeps the number from going negative. It is shorter, though the `if` version is easier to read when you are starting out.

## What I would improve next

- **Keyboard support:** let the left and right arrow keys change slides.
- **Responsive width:** replace the fixed `width: 500px` with `width: min(500px, 100%)`.
- **Descriptive alt text:** say what each picture shows instead of "Image 1".
- **Dot indicators:** show where you are in the set.
- **Transitions:** fade between slides. `display` alone won't give a simple fade, so stack the slides and animate `opacity`.
- **Autoplay:** if you add it, include a pause control.
