Automatic Card Carousel In Vanilla JavaScript – vanilla-img-slideshow

Category: Javascript , Slider , Slideshow | November 3, 2018
Author:JHerbranson
Views Total:1,627 views
Official Page:Go to website
Last Update:November 3, 2018
License:MIT

Preview:

Automatic Card Carousel In Vanilla JavaScript – vanilla-img-slideshow

Description:

An automatic image slideshow in vanilla JavaScript that cycles through a group of images just like a card. Smooth animations based on CSS3 transforms and transitions.

How to use it:

Insert a group of images into the slideshow.

<div id="mySlideshow">
  <img class="gallery-item" src="1.jpg" alt="pic1">
  <img class="gallery-item" src="2.jpg" alt="pic2">
  <img class="gallery-item" src="3.jpg" alt="pic3">
  <img class="gallery-item" src="4.jpg" alt="pic4">
  <img class="gallery-item" src="5.jpg" alt="pic5">
  ...
</div>

The necessary CSS/CSS3 rules for the slideshow.

#mySlideshow {
  margin: 50px auto 0;
  max-width: 600px;
  height: 300px;
  position: relative;
  overflow: hidden;
}
img {
  transform: translate(600px);
  position: absolute;
  width: 100%;
}
.showcase-img {
  transform: translate(0);
  transition: .6s;
}
.showcase-left {
  transform: translate(-600px);
  transition: .6s;
}

The main JavaScript to enable the slideshow.

const images = document.querySelectorAll(".gallery-item");
let timmer = setInterval(cycleImage, 4000);
// Will always stay the same
const length = images.length;
// Will increment by one everytime the function is called.
let imageCounter = images.length;
// e.g. 3 % 3 = 0, 4 % 3 = 1, 5 % 3 = 2, etc.
// loops through the array like this, using the remainder as the index number
function cycleImage() {
  //the new item in the array shown
  let newIndex = imageCounter % length;
  //the previous item in the array
  let lastIndex = 0;
  newIndex === 0 ? lastIndex = length - 1 : lastIndex = newIndex - 1;
  //the item before lastIndex
  //moves it back to rest on the right side
  let moveIndexRight = 0;
  lastIndex === 0 ? moveIndexRight = length - 1 : moveIndexRight = lastIndex - 1;
  images[newIndex].classList.add("showcase-img");
  images[lastIndex].classList.remove("showcase-img");
  images[lastIndex].classList.add("showcase-left");
  images[moveIndexRight].classList.remove("showcase-left");
  imageCounter++;
}
cycleImage();

You Might Be Interested In:


Leave a Reply