Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Created July 17, 2012 15:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ksafranski/3130239 to your computer and use it in GitHub Desktop.
Save ksafranski/3130239 to your computer and use it in GitHub Desktop.
Simple jQuery Rotator with all the goodies
/*
*
* Another fine bit of code by Kent Safranski < http://www.fluidbyte.net >
*
* HTML:
* <ul id="banner">
* <li>Stuff</li>
* ...
* </ul>
*
* CSS:
* #banner { position: relative; margin: 0; padding: 0; }
* #banner li { display: none; position: absolute; box-sizing: border-box; list-style: none; width: 600px; height: 200px; }
* #banner li:first-child { display: block; }
*
* JAVASCRIPT:
* $('#banner').rotate();
*
*/
jQuery.fn.rotate = function(o){
var o = jQuery.extend({
children : 'li',
delay : 3000,
speed : 300,
hover : true, // Pause on hover?
next : $('#button-next'),
prev : $('#button-prev')
},o);
$(this).each(function(){
var r = $(this);
var current = 0;
var total = r.children(o.children).length;
// Manually move next
o.next.click(function(){
if(current==(total-1)){ current=0; }else{ current++; }
rotator.goto(current);
});
// Manually move next
o.prev.click(function(){
if(current==0){ current=(total-1); }else{ current--; }
rotator.goto(current);
});
var rotator = {
go : function(){
automation = setInterval(function(){
rotator.goto(current);
if(current==(total-1)){ current=0; }else{ current++; }
}, o.delay);
},
goto : function(i){
r.children(o.children).eq(i).stop(true,true).fadeIn(o.speed).siblings().fadeOut(o.speed);
},
stop : function(){
clearInterval(automation);
}
}
// Pause on hover (?)
if(o.hover){ r.hover(function(){ rotator.stop(); },function(){ rotator.go(); }); }
// Start
rotator.go();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment