A lightweight JavaScript Image Carousel

by Julien Etienne

HTML

<figure></figure>
<!--
A minimalistic JavaScript Image Carousel. Clean, light weight & easy on memory.

Extending it is easy: 
Add event listeners for buttons, add/subtract from count in a function, update the src. Enjoy - Julien
-->

CSS

body, html {
  background: #222;
}

figure {
  position: absolute;
}

JavaScript

(function() {
  var opt = {
    speed: 3, // Seconds  
    width: '50%', // '500px' / '50%'
    height: 'auto' // '300px' / 'auto' / '30%'
  }

  // Your images
  var images = [
    'http://imageshack.com/a/img661/4783/atcJHi.jpg',
    'http://imageshack.com/a/img540/1278/tC7r6R.jpg',
    'http://imageshack.com/a/img633/5291/sM7HvX.jpg',
    'http://imageshack.com/a/img908/7354/b8CBA7.jpg',
    'http://imageshack.com/a/img538/4448/zzCFM0.jpg',
    'http://imageshack.com/a/img901/1690/upfsuw.jpg',
    'http://imageshack.com/a/img538/9254/uWuuJX.jpg',
    'http://imageshack.com/a/img911/5175/MHox11.jpg',
    'http://imageshack.com/a/img540/9766/OkhZjk.jpg'
  ];

  // Change this to 'div' & in the HTML to support old browsers
  var figure = document.getElementsByTagName('figure')[0];
  figure.style.width = opt.width;
  figure.style.height = opt.height;
  var img = document.createElement('img');
  img.style.width = '100%'
  img.style.height = opt.height;
  // Append the image to the slideshow container
  figure.appendChild(img);
  // Basic request animation polyfill 
  var rAF = window.requestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    function(callback) {
      return setTimeout(callback, 1000 / 60);
    };
  // declare var count outside of rAF loop
  var count;
  // Where the magic happens
  function changeImage(timeStamp) {
    count = Math.floor(timeStamp / 1000 / opt.speed);
    while (count > images.length - 1) {
      count -= images.length;
    }
    img.src = images[count];
    rAF(changeImage);
  }
  rAF(changeImage); // Party starter
}());