Skip to content

Instantly share code, notes, and snippets.

@henkman
Created September 16, 2015 15:38
Show Gist options
  • Select an option

  • Save henkman/8371aba4cc9653f896a0 to your computer and use it in GitHub Desktop.

Select an option

Save henkman/8371aba4cc9653f896a0 to your computer and use it in GitHub Desktop.
Imageslider with smooth transition (no dependency)
function newSlider(document, window) {
function start($slider, images, currentImage, interval, fadeInDuration) {
var currentBuffer = 0;
var $buffers = [
document.createElement("img"),
document.createElement("img")
];
for(var i=0; i<$buffers.length; i++) {
$buffers[i].src = images[currentImage];
$buffers[i].style.position = "absolute";
$buffers[i].style.top = 0;
$buffers[i].style.left = 0;
$buffers[i].style.width = "100%";
$buffers[i].style.height = "100%";
$buffers[i].style.position = "absolute";
$buffers[i].style.opacity = 0;
$slider.appendChild($buffers[i]);
}
$buffers[currentBuffer].style.opacity = 1.0;
function fade($elem, begin, from, to) {
var now = new Date().getTime();
var opacity = from + (to - from) * (now - begin) / fadeInDuration;
if (opacity<0) {
$elem.style.opacity = 0;
} else if (opacity>1) {
$elem.style.opacity = 1;
} else {
$elem.style.opacity = opacity;
window.setTimeout(function(){ fade($elem, begin, from, to); }, 1);
}
}
function next($slider) {
currentImage++;
if(currentImage >= images.length) {
currentImage = 0;
}
var nextBuffer = currentBuffer+1;
if(nextBuffer >= $buffers.length) {
nextBuffer = 0;
}
$buffers[nextBuffer].src = images[currentImage];
fade($buffers[currentBuffer], new Date().getTime(), 1.0, 0.0);
fade($buffers[nextBuffer], new Date().getTime(), 0.0, 1.0);
currentBuffer = nextBuffer;
}
window.setInterval(function(){ next($slider); }, interval);
}
return {
init: function() {
var $sliders = document.querySelectorAll("[data-slider]");
for(var i=0; i<$sliders.length; i++) {
var images = $sliders[i].getAttribute("data-slider");
if(!images) {
continue;
}
images = images.split(",");
if(images.length == 0) {
continue;
}
var interval = $sliders[i].getAttribute("data-slider-interval");
if(interval) {
interval = parseInt(interval, 10);
} else {
interval = 5000;
}
var fadeInDuration = $sliders[i].getAttribute("data-slider-fadein");
if(fadeInDuration) {
fadeInDuration = parseInt(fadeInDuration, 10);
} else {
fadeInDuration = 1000;
}
start($sliders[i], images, 0, interval, fadeInDuration);
}
}
}
}
var Slider = newSlider(document, window);
Slider.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment