Simplest Image Carousel In Vanilla JavaScript

Category: Javascript , Slider | June 2, 2017
Author: Juandresyn
Views Total: 2,410
Official Page: Go to website
Last Update: June 2, 2017
License: MIT

Preview:

Simplest Image Carousel In Vanilla JavaScript

Description:

A minimal dependency-free JavaScript library for creating a responsive, cross-fading image carousel with touch gestures support.

How to use it:

Add your images as backgrounds to the carousel:

<section class="slider-main">
  <button class="js-prev slider-arrows slider-arrows--prev"><</button>
  <ul class="js-slider slider-home">
    <li class="js-slider-item slider-main__item has-background-image active" style="background-image: url('1.jpg')"></li>
    <li class="js-slider-item slider-main__item has-background-image" style="background-image: url('2.png')"></li>
    <li class="js-slider-item slider-main__item has-background-image" style="background-image: url('3.png')"></li>
  </ul>
  <button class="js-next slider-arrows slider-arrows--next">></button>
</section>

The primary CSS styles for the carousel.

.slider-main {
  height: 65vh;
  position: relative;
  background-color: #888;
}

@media screen and (max-width: 778px) {

.slider-main { height: 35vh; }
}

@media screen and (max-width: 690px) {

.slider-main { height: 55vh; }
}

@media screen and (max-width: 480px) {

.slider-main { height: 180px; }
}

.slider-main__item {
  width: 100%;
  height: 65vh;
  position: absolute;
  z-index: 10;
  opacity: 0;
  -webkit-transition: all 0.5s ease-in-out;
  -moz-transition: all 0.5s ease-in-out;
  -o-transition: all 0.5s ease-in-out;
  transition: all 0.5s ease-in-out;
}

@media screen and (max-width: 778px) {

.slider-main__item { height: 35vh; }
}

@media screen and (max-width: 690px) {

.slider-main__item { height: 55vh; }
}

@media screen and (max-width: 480px) {

.slider-main__item { height: 180px; }
}

.slider-main__item.active {
  z-index: 11;
  opacity: 1;
}

.slider-home {
  position: relative;
  list-style-type: none;
  padding: 0;
}

Style and position the navigation arrows in the CSS:

.slider-arrows {
  position: absolute;
  z-index: 15;
  border: 0;
  background: none;
  font-size: 45px;
  color: #5a5a5a;
  cursor: pointer;
  padding: 10px;
  top: calc(50% - 55px);
}

@media screen and (max-width: 480px) {

.slider-arrows { top: calc(90% - 55px); }
}

.slider-arrows:hover { color: #888; }

.slider-arrows--prev { left: 20px; }

@media screen and (max-width: 480px) {

.slider-arrows--prev { left: 0; }
}

.slider-arrows--next { right: 20px; }

@media screen and (max-width: 480px) {

.slider-arrows--next { right: 0; }
}

Load the main JavaScript file ‘slider.js’ at the end of the html document. That’s it.

<script src="src/js/slider.js"></script>

 

You Might Be Interested In:


Leave a Reply