We will create an image slider in JavaScript, CSS and HTML. The slider will be able to scroll through pictures automatically and with back and forward buttons and transition effect.

Create HTML markup for the slider, including an image container, forward and backward buttons, and styling classes.

<!DOCTYPE html>
  <title>Image Slider</title>
  <link rel="stylesheet" href="style.css">

  <div id="slider">
    <div class="slider-container">
      <img src="images/img1.jpeg" alt="image1" class="active">
      <img src="images/img2.jpeg" alt="image2">
      <img src="images/img3.jpeg" alt="image3">
    <div class="buttons">
      <button class="prev">Previous</button>
      <button class="next">Next</button>

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

Write JavaScript code to handle button clicks and display the next or previous image. Use querySelectorAll to get all the images in the slider and classList.add and classList.remove to control the active class.

const images = document.querySelectorAll('.slider-container img');
const prev = document.querySelector('.prev');
const next = document.querySelector('.next');
let current = 0;

prev.addEventListener('click', () => {
  if (current < 0) {
    current = images.length - 1;

next.addEventListener('click', () => {
  if (current === images.length) {
    current = 0;

This code creates a slider with forward and back buttons that allow you to switch images manually. The transition effect between images is created using CSS animation.

However, this code is basic and can be extended and modified to add additional features such as slide indicators, responsive design, and so on.

We can add functionality to automatically switch slides at 3 second intervals.

// Автоматически перелистываются картинки каждые 3 секунды
setInterval(() => {
  if (current === images.length) {
    current = 0;
}, 3000);

Adding Basic Styles with CSS

#slider {
  width: 500px;
  height: 500px;
  margin: 0 auto;
  position: relative;

.slider-container img {
  transition: all 0.5s ease;
  opacity: 0;
  width: 100%;
  position: absolute;
  z-index: 1;

.slider-container img.active {
  opacity: 1;

.buttons {
  position: relative;
  z-index: 2;

.buttons button {
  border: 1px solid #ccc;
  width: 100px;
  height: 50px;
  line-height: 50px;
  text-align: center;
  color: #fff;
  background-color: black;
  font-weight: bold;
  opacity: 0.9;

.buttons button:hover {
  opacity: 0.6;
  cursor: pointer;

Our simple slider is ready to use.

Comments to: How to create an image slider in JavaScript

    Your email address will not be published. Required fields are marked *

    Attach images - Only PNG, JPG, JPEG and GIF are supported.