Author Photo
Christopher Unum I am a software Developer, I write web development tutorials, I also mentor aspiring web developers. s

how to create a simple image slideshow using html, css and javascript



By using slideshows you can showcase information in a compressed and organized format. With slideshows, information can be accessed quickly without using the mouse or scrolling vertically. In this tutorial, we will be creating a simple slideshow that takes an array of image URLs and converts them into a slideshow.

Prerequisite

Basic knowledge of html, css and JavaScript is needed to fully grasp the concept in this tutorial.

Html

<img src="" width="100%" id="showcase" />

<center>
  <div id="captions"></div>
</center>


CSS

body {
  margin0;
}

#captions {
  displayinline-block;
  margin0 auto;
}
.bullet {
  cursorpointer;
  height15px;
  width15px;
  margin10px 5px;
  background-color#bbb;
  border-radius50%;
  displayinline-block;
  transition: background-color 0.6s ease;
}
.current {
  background#e98b10;
}


JavaScript

const imagesUrlArray = [
  "images/Slide1.jpg",
  "images/Slide2.jpg",
  "images/Slide3.jpg",
  "images/Slide4.jpg",
  "images/Slide5.jpg",
  "images/Slide6.jpg",
];
let lastCurrent = 0;

const createBullets = (length) => {
  for (let i = 0; i < length; i++) {
    let bullet = document.createElement("span");
    bullet.classList.add("bullet");
    document.querySelector("#captions").appendChild(bullet);
  }
};

createBullets(imagesUrlArray.length);

bullets = document.querySelectorAll(".bullet");
bullets[0].classList.add("current");
for (let i = 0; i < bullets.length; i++) {
  bullets[i].addEventListener("click", () => {
    document.querySelector("#showcase").src = imagesUrlArray[i];
    bullets[i].classList.add("current");
    bullets[lastCurrent].classList.remove("current");
    lastCurrent = i;
    clearInterval(interval);
    startSlideshow();
  });
}

let interval = undefined;
const startSlideshow = () => {
  let x = lastCurrent;
  interval = setInterval(function () {
    x = x == 5 ? 0 : ++x;
    displayImage(x);
  }, 3000);
};

startSlideshow();
const displayImage = (id) => {
  document.querySelector("#showcase").src = imagesUrlArray[id];
  bullets[id].classList.add("current");
  bullets[lastCurrent].classList.remove("current");
  lastCurrent = id;
};


Conclusion

Slideshows are  very pleasant and popular way to view images and everyone knows how to use it. As seen above, creating it is pretty straight forward.