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!
TABLE OF CONTENTS
JAVASCRIPT SLIDESHOW
All right, let us now get into a demo of the Javascript slideshow – Also, some details on how it works.
HOW TO USE & DEMO
<!-- (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.png", cap: "Girl eating flower in library."},
{src: "slide-b.png", cap: "Girl eating cactus."},
{src: "slide-c.png", cap: "Girl eating seafood in sea."}
],
auto: 3000 // (optional) 3 sec per slide, remove to manual scroll
}));
</script>
- Captain Obvious at your service, load both
slides.css
andslides.js
. - Define a
<div>
to attach the slideshow to. - 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.
PART 1) ATTACH HTML INTERFACE
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 = "<";
sRight.innerHTML = ">";
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
// (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
// (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
/* (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.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE 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.
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
- Arrow Functions – CanIUse
- CSS Flexbox – CanIUse
Should work across all major browsers… Less the “ancient ones”.
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!
Hi!
I have installed and I tried to use it.
Most of functions are ok, buk I am not able to set the pictures in slideshow to be placed in the center of the screen. All pictures are aligned to the left margin…
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!
It works… But that’s a server-side script, the server needs to support PHP.
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.
JPG and jpg are the same, just case-sensitive. Don’t understand why Canon insists on using upper-case…
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.