Minimal HTML5/JavaScript/CSS Image Slider

Category: Javascript , Slider | March 23, 2015
Author:leandrow
Views Total:2,588 views
Official Page:Go to website
Last Update:March 23, 2015
License:MIT

Preview:

Minimal HTML5/JavaScript/CSS Image Slider

Description:

A simple slider which allows you to automatically and infinitely circle through a group of images with CSS3 powered crossfade effects, built using Html5, pure JavaScript and CSS/CSS3.

How to use it:

Wrap your images using HTML5 figure tag. The slider will automatically generate image captions from img’s alt attribute and display them in the figcaption tag.

<div class="slider">
  <figure>
    <a href="#" class="effect">
      <img src="img/1.png" alt="Text 1">
    </a>
    <a href="#" class="effect">
      <img src="img/2.png" alt="Text 2">
    </a>
    <a href="#" class="effect">
      <img src="img/3.png" alt="Text 3">
    </a>
    <a href="#" class="effect">
      <img src="img/4.png" alt="Text 4">
    </a>
  </figure>
  <figcaption></figcaption>
</div>

The core CSS/CSS3 rules for the image slider.

.slider {
  width: 490px;
  height: 125px;
  position: relative;
  margin: auto;
  top: 112px;
}
.effect { transition: all ease-out 0.5s; }
figure a {
  width: 100px;
  height: 125px;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
figcaption {
  width: 390px;
  height: 125px;
  float: right;
  padding: 40px 20px;
  box-sizing: border-box;
}
.active { opacity: 1; }

The JavaScript to active the image slider.

function slider(){
  var config = {
    // Set first image of slider
    img: function(){
      element = document.querySelector(".slider a:first-child");
      element.classList.add("active");
      this.legend(element);
    },
    // Add legend in the figcaption
    legend: function(obj){
      var legend = obj.querySelector("img").getAttribute("alt");
      document.querySelector("figcaption").innerHTML = legend;
    },
    // Add class in the next slider
    slide: function(){
      element = document.querySelector(".active");
      if(element.nextElementSibling){
        element.nextElementSibling.classList.add("active");
        config.legend(element.nextElementSibling);
        element.classList.remove("active");
      }
      else {
        element.classList.remove("active");
        config.img();
      }
    }
  }
  config.img();
  config.legend(element);
  // Interval of slides
  var auto = setInterval(config.slide,4000);
}
// Run when loading window
window.addEventListener("load",slider,false);

You Might Be Interested In:


Leave a Reply