Flexbox Based Responsive Image Slider

Category: Javascript , Slider | August 10, 2017
Author: kathykato
Views Total: 165
Official Page: Go to website
Last Update: August 10, 2017
License: MIT

Preview:

Flexbox Based Responsive Image Slider

Description:

A dead simple, fully responsive image slider built using JavaScript and CSS flexbox.

How to use it:

Add a group of images to the slider.

<div class="slider">
  <img class="active" src="1.jpg">
  <img src="2.jpg">
  <img src="3.jpg">
  ...
</div>

Create a slider navigation to switch between images.

<nav class="slider-nav">
  <ul>
    <li class="arrow">
      <a class="previous">
        <span>
          <
        </span>
      </a>
    </li>
    <li class="arrow">
      <a class="next">
        <span>
          >
        </span>
      </a>
    </li>
  </ul>
</nav>

The primary CSS for the image slider.

.slider-nav ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: -webkit-box;
  display: flex;
  -webkit-box-pack: center;
  justify-content: center;
}

.slider-nav li {
  -webkit-box-flex: 2;
  flex: 2;
  text-align: center;
  display: -webkit-box;
  display: flex;
}

img {
  max-width: 100%;
  display: none;
  -webkit-box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2);
  -moz-box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2);
  box-shadow: 10px 10px 20px 0 rgba(94,47,59,0.2);
}

img.active {
  display: block;
  -webkit-animation: fadeImg 0.8s;
  -moz-animation: fadeImg 0.8s;
  animation: fadeImg 0.8s;
}

.slider-nav .arrow { flex: 0 0 15%; }

.slider-nav a {
  flex-basis: 100%;
  display: -webkit-box;
  display: flex;
  -webkit-box-align: center;
  align-items: center;
}

.slider-nav span {
  display: block;
  width: 100%;
}

Apply a fading effect to the images when switching.

@-webkit-keyframes 
fadeImg {  from {
 opacity: 0;
}

to { opacity: 1; }
}

@-moz-keyframes 
fadeImg {  from {
 opacity: 0;
}

to { opacity: 1; }
}

@keyframes 
fadeImg {  from {
 opacity: 0;
}

to { opacity: 1; }
}

The main JavaScript to activate the image  slider.

const items = document.querySelectorAll('img');
const itemCount = items.length;
const nextItem = document.querySelector('.next');
const previousItem = document.querySelector('.previous');
let count = 0;

function showNextItem() {
  items[count].classList.remove('active');

  if(count < itemCount - 1) {
    count++;
  } else {
    count = 0;
  }

  items[count].classList.add('active');
  console.log(count);
}

function showPreviousItem() {
  items[count].classList.remove('active');

  if(count > 0) {
    count--;
  } else {
    count = itemCount - 1;
  }

  items[count].classList.add('active');
  console.log(count);
}

nextItem.addEventListener('click', showNextItem);
previousItem.addEventListener('click', showPreviousItem);