Last Updated: September 09, 2019
·
5.827K
· bunkerbewohner

Dead Simple Slideshows with JS and CSS

Slideshows are often at the center of attention and used for photo galleries or on the big center stages of many contemporary websites. While in the past Adobe Flash was often the tool of choice using CSS3 and JavaScript slideshows can be easily implemented without a lot of code.

The technique I'm using here is one of the easiest ways to realize a simple slideshow with a nice cross-fading transition effect using only standard JavaScript and CSS3.

The base markup is trivial. Just put a few images into a div container:

 <div class="slides">
  <img src="http://lorempixel.com/500/300/?r=1">
  <img src="http://lorempixel.com/500/300/?r=2">
  <img src="http://lorempixel.com/500/300/?r=3">
  <img src="http://lorempixel.com/500/300/?r=4">
  <img src="http://lorempixel.com/500/300/?r=5">
</div>

Stack all pictures over each other within the container using CSS and define the transitions (browser specific prefixed may have to be used for transitions):

/* the slide container with a fixed size */
.slides {
  box-shadow: 0px 0px 6px black;
  margin: 0 auto;
  width: 500px;
  height: 300px;
  position: relative;
}

/* the images are positioned absolutely to stack. opacity transitions are animated. */
.slides img { 
  display: block;
  position: absolute; 
  transition: opacity 1s;
  opacity: 0;
  width: 100%;
}

/* the first image is the current slide. it's faded in. */
.slides img:first-child { 
  z-index: 2; /* frontmost */
  opacity: 1;
}

/* the last image is the previous slide. it's behind the current slide and it's faded over. */
.slides img:last-child {
  z-index: 1; /* behind current slide */
  opacity: 1;
}

After this simple setup, all there's left is to change the order of slides to advance the slideshow. The following snippet periodically moves the first image (current slide) to the end of the container, thus making the next image the current slide. The change is animated with a cross-fade thanks to the CSS rules defined above.

function nextSlide() {
    var q = function(sel) { return document.querySelector(sel); }   
    q(".slides").appendChild(q(".slides img:first-child"));
}
setInterval(nextSlide, 3000)

And that's all there is to it. I uploaded the complete example to JSFiddle.

2 Responses
Add your response

Hi, thanks for this really simple snippet.
However I have copy/pasted your code and the css fading transition does not work in any browser (latest versions) but works when displayed in your JSFiddle. Any idea?

over 1 year ago ·

Hi, try putting this into an empty HTML file:
http://pastebin.com/pZcWCpQw

It should work. Maybe there's a conflict with whatever is on the page you have been adding it to. If it doesn't work check your browser's developer console for hints about unknown css properties (missing vendor prefix?) or JavaScript errors.

over 1 year ago ·