Skip to content

Instantly share code, notes, and snippets.

@tincho
Created December 29, 2016 15:18
Show Gist options
  • Save tincho/29a4eeb85ffe25596aa70f3a1b45c52e to your computer and use it in GitHub Desktop.
Save tincho/29a4eeb85ffe25596aa70f3a1b45c52e to your computer and use it in GitHub Desktop.
/**
* vainilla js simple slider
* source: http://cssdeck.com/labs/image-slider-1
*/
/**
css:
.image-slider-wrapper{
overflow: hidden;
}
#image_slider{
position: relative;
overflow: hidden;
height: 280px;
padding:0;
left:0;
}
#image_slider li{
position:relative;
max-width: 100%;
float:left;
list-style: none;
left: 0;
}
******* markup *****
<div class="image-slider-wrapper">
<ul id="image_slider">
<li><img src="1.jpg"></li>
<li><img src="2.jpg"></li>
<li><img src="3.jpg"></li>
</ul>
<div class="pager">
</div>
</div>
*/
var ul;
var li_items;
var li_number;
var image_number = 0;
var slider_width = 0;
var image_width;
var current = 0;
function init() {
ul = document.getElementById('image_slider');
li_items = ul.children;
li_number = li_items.length;
for (i = 0; i < li_number; i++) {
// nodeType == 1 means the node is an element.
// in this way it's a cross-browser way.
//if (li_items[i].nodeType == 1){
//clietWidth and width???
image_width = li_items[i].childNodes[0].clientWidth;
slider_width += image_width;
image_number++;
}
ul.style.width = parseInt(slider_width) + 'px';
slider(ul);
}
function slider() {
animate({
delay: 11,
duration: 1100,
delta: function(p) {
return Math.max(0, -1 + 2 * p);
},
step: function(delta) {
ul.style.left = '-' + parseInt(current * image_width + delta * image_width) + 'px';
},
callback: function() {
current++;
if (current < li_number - 1) {
slider();
} else {
var left = (li_number - 1) * image_width;
setTimeout(function() {
goBack(left);
}, 2000);
setTimeout(slider, 4000);
}
}
});
}
function goBack(left_limits) {
current = 0;
setInterval(function() {
if (left_limits >= 0) {
ul.style.left = '-' + parseInt(left_limits) + 'px';
left_limits -= image_width / 10;
}
}, 17);
}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {
clearInterval(id);
opts.callback();
}
}, opts.dalay || 17);
}
window.onload = init;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment