Skip to content

Instantly share code, notes, and snippets.

@endorfin
Created December 11, 2011 20:18
Show Gist options
  • Save endorfin/1462519 to your computer and use it in GitHub Desktop.
Save endorfin/1462519 to your computer and use it in GitHub Desktop.
JS: Simple Infinite Carousel - jQuery Version
/*
* Simple Infinite Carousel - jQuery Version
*
* Released on 11th December 2011.
*
* Copyright (c) 2010-2011 René Kersten, http://pixel-webarts.de
*
* Licensed under the terms of MIT License.
*
*/
var PixelCarousel = function(dom_element, options)
{
this.autostart = options.autostart || true;
this.pauseTime = options.pauseTime || 6000;
this.carousel = $(dom_element);
this.list = this.carousel.find('> ul');
if(this.list)
{
this.index = 1;
this.items = this.list.children();
this.itemWidth = this.items.width();
this.itemsTotal = this.items.length;
this.itemsVisible = Math.round(this.carousel.width() / this.itemWidth);
this.increment = this.itemWidth;
this.isAnimating = false;
this.init();
}
};
PixelCarousel.prototype = {
init: function()
{
var that = this;
that.carousel.addClass('carousel');
that.list.wrap('<div class="wrapper"></div>');
if(that.itemsTotal > that.itemsVisible)
{
for (var i = 0; i < that.itemsVisible; i++) {
that.list.css('width',(that.itemsTotal+that.itemsVisible)*that.increment + that.increment + 'px');
that.list.append($(that.items[i]).clone());
}
// add prev/next button
var prevBtn = $('<a class="prev">prev</a>').bind('click', function(event){
event.preventDefault();
that.prev();
});
var nextBtn = $('<a class="next">next</a>').bind('click', function(event){
event.preventDefault();
that.next();
});
that.carousel.append(prevBtn, nextBtn);
// stop on hover
that.carousel.hover(function(){
that.stop();
}, function(){
that.start();
});
if(that.autostart){ that.start(); }
}
},
start: function()
{
var that = this;
that.paused = false;
if(that.itemsTotal > that.itemsVisible){
that.timer = setInterval(function(){ that.next() }, that.pauseTime);
}
},
stop: function()
{
this.paused = true;
clearInterval(this.timer);
},
prev: function()
{
var that = this;
if (!that.isAnimating) {
if (that.index == 1) {
that.list.css('left', '-' + that.itemsTotal * that.itemWidth + 'px');
that.index = that.itemsTotal;
}
else {
that.index--;
}
that.list.animate({
left: '+=' + that.increment,
y: 0,
queue: true
}, 'swing', function(){ that.isAnimating = false; });
that.isAnimating = true;
}
},
next: function()
{
var that = this;
if (!that.isAnimating) {
if (that.index > that.itemsTotal) {
that.index = 2;
that.list.css('left', '0px');
}
else {
that.index++;
}
that.list.animate({
left: '-=' + that.increment,
y: 0,
queue: true
}, 'swing', function(){ that.isAnimating = false; });
that.isAnimating = true;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment