Simple Responsive Slideshow With CSS JS (Free Download)

Welcome to a tutorial on how to create a simple responsive slideshow with pure CSS and vanilla Javascript. Yes, there are a lot of crazy slideshow plugins on the Internet. But some of them require the use of third-party libraries, which adds to the undesired loading bloat – So here it is, a simple and lightweight slideshow that you can use. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

TABLE OF CONTENTS

 

 

DOWNLOAD & DEMO

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

SOURCE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

HOW TO USE & DEMO

slides.html
<!-- (A) LOAD LIBRARY -->
<link rel="stylesheet" href="slides.css">
<script defer src="slides.js"></script>

<!-- (B) EMPTY HTML DIV -->
<div id="demo"></div>

<!-- (C) ATTACH SLIDESHOW -->
<script>
window.addEventListener("load", () => sslide({
  target: document.getElementById("demo"),
  images: [
    {src: "slide-a.webp", cap: "Girl eating flower in library."},
    {src: "slide-b.webp", cap: "Girl eating cactus."},
    {src: "slide-c.webp", cap: "Girl eating seafood in sea."}
  ],
  auto: 3000 // (optional) 3 sec per slide, remove to manual scroll
}));
</script>
  1. Captain Obvious at your service, load both slides.css and slides.js.
  2. Define a <div> to attach the slideshow to.
  3. Lastly, use sslide() to attach the slideshow. There are only 3 options here:
    • target The <div> element that you want to attach the slideshow to.
    • images Array of images you want to show. Remember to provide both the source URL and caption.
    • auto In milliseconds, optional. Automatically rotate between the slides.

 

 

HOW IT WORKS

Now for those who are interested in “deep customizing” the slideshow – Here is the Javascript and a quick walkthrough.

 

PART 1) ATTACH HTML INTERFACE

slides.js
function sslide (instance) {
  // (A) BUILD HTML INTERFACE
  var sImg = document.createElement("img"),
      sCaption = document.createElement("div"),
      sLeft = document.createElement("div"),
      sRight = document.createElement("div");
      instance.target.className = "sSlide hide";
      sImg.className = "sImg";
      sCaption.className = "sCaption";
      sLeft.className = "sLeft";
      sRight.className = "sRight";
      sLeft.innerHTML = "&lt;";
      sRight.innerHTML = "&gt;";
  instance.target.appendChild(sImg);
  instance.target.appendChild(sCaption);
  instance.target.appendChild(sLeft);
  instance.target.appendChild(sRight);
  // ...
}

Ok, this looks crazy. But all it does is essentially generate the following HTML:

<div id="demo" class="sSlide hide">
  <div class="sImg"></div>
  <div class="sCaption"></div>
  <div class="sLeft" onclick="shift()"></div>
  <div class="sRight" onclick="shift(1)"></div>
</div>

Take note of the hide CSS class here. We will not show the slideshow until all images are properly loaded.

 

 

PART 2) SHIFT SLIDE

slides.js
// (B) AUTO SHIFT SLIDE
if (instance.auto) {
  var auto = () => {
    if (instance.timer) { clearInterval(instance.timer); }
    instance.timer = setInterval(() => shift(1), instance.auto);
  };
}

// (C) SHIFT SLIDE
instance.now = -1; // current slide
var shift = direction => {
  // (C1) CALCULATE NEXT SLIDE
  if (direction) { instance.now++; } else { instance.now--; }
  if (instance.now < 0) { instance.now = instance.images.length - 1; }
  if (instance.now >= instance.images.length) { instance.now = 0; }
 
  // (C2) DRAW SLIDE
  sImg.src = instance.images[instance.now].src;
  sCaption.innerHTML = instance.images[instance.now].cap;
 
  // (C3) AUTO SHIFT SLIDE
  if (instance.auto) { auto(); }
}
sLeft.onclick = () => shift();
sRight.onclick = () => shift(1);

Should not be much trouble.

  • We use instance.now to track the current slide.
  • When the user clicks on last/next, we subtract/add instance.now accordingly.
  • Then, set the image and caption.

 

PART 3) PRELOAD IMAGES

slides.js
// (D) PRELOAD IMAGES
var loaded = 0;
for (let i of instance.images) {
  let img = new Image();
  img.src = i.src;
  img.onload = () => {
    loaded++;
    if (loaded == instance.images.length) {
      shift(1);
      instance.target.classList.remove("hide");
      if (instance.auto) { auto(); }
    }
  };
}

To prevent “missing slides”, this little snippet will wait until all images are loaded before showing the slideshow.

 

 

PART 4) THE CSS

slides.css
/* (A) WHOLE PAGE */
* {
  font-family: Arial, Helvetica, sans-serif;
  box-sizing: border-box;
}
 
/* (B) SHARED */
.sImg, .sCaption { width: 100%; }
.sSlide, .sLeft, .sRight { display: flex; }
 
/* (C) CONTAINER */
.sSlide {
  flex-wrap: wrap;
  position: relative;
  max-width: 640px;
}
 
/* (D) IMAGE */
.sImg {
  height: 350px;
  object-fit: cover; /* fill, contain, scale-down */
}

/* (E) CAPTION */
.sCaption {
  padding: 10px;
  color: #fff;
  background: #000;
}
 
/* (F) CONTROLS */
/* (F1) LEFT/RIGHT BUTTONS */
.sLeft, .sRight {
  align-items: center;
  position: absolute;
  top: 0;
  z-index: 9;
  height: 100%;
  padding: 0 20px;
  font-size: 2em;
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  cursor: pointer;
}
.sTop .sLeft { left: 0; }
.sTop .sRight { right: 0; }
 
/* (F2) SHOW ONLY ON HOVER */
.sLeft, .sRight {
  visibility: hidden;
  opacity: 0;
  transition: opacity 0.3s;
}
.sSlide:hover .sLeft, .sSlide:hover .sRight {
  visibility: visible;
  opacity: 1;
}

Yep… Don’t think I want to dive too deep into the CSS – These are practically the cosmetics of the slideshow. Feel free to change the colors and layout to fit your own theme.

 

 

EXTRAS BITS & LINKS

That’s it for the simple slideshow, and here is a small extra that you may find useful.

 

USING PHP TO AUTOLOAD ALL SLIDES

Lazy to change the HTML every time? Use a server-side script to help you extract all the image files automatically. Here’s a quick example in PHP.

<script>
window.addEventListener("DOMContentLoaded", () => {
  sslide.init({
    target: "slidedemo",
    images: [<?php
      $dir = "gallery/";
      $images = glob($dir . "*.{jpg,jpeg,gif,png,bmp,webp}", GLOB_BRACE);
      $all = count($images);
      $last = $all - 1;
      for ($i=0; $i<$all; $i++) {
        printf('{src:"%s%s", cap:"%s"}%s',
          $dir, basename($images[$i]), basename($images[$i]),
          $i==$last ? "" : ","
        );
      }
    ?>]
});
</script>

 

COMPATIBILITY CHECKS

Should work across all major browsers… Less the “ancient ones”.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to create a simple slideshow for your project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

5 thoughts on “Simple Responsive Slideshow With CSS JS (Free Download)”

  1. Richard Greenhorn

    Excellent! Thanks for this, it was just what I needed.
    One small issue with the extra bit (the lazy code as you call it). I couldn’t get this to work initially and think you have a }); missing towards the end.
    Other than that – perfect!

  2. I have just installed this, it is great and just what I needed. However when I loaded my own images they did not display, as my Canon camera saves as .JPG files (not .jpg) so I added JPG to the file types in gallery.php (line 14). Now it works, but I wonder if I should just rename all my JPG files to jpg instead.

  3. That was nice. Simple add useful. I also have added a few lines to code and I would like to share… You can contact me via my e-mail if you would like to.

Leave a Comment

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