/ Published in: jQuery
parameters:
ul containing carousel,
next btn
prev btn
ul containing carousel,
next btn
prev btn
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* carousel */ function carouselFunc(carousel,nextBtn,prevBtn) { //passed variables var carousel = carousel; var nextBtn = nextBtn; var prevBtn = prevBtn; var carouselInterval = 5000; var carouselId = $(carousel).attr("id"); var carouselItemWidth = $(carousel).find("li:first").outerWidth(); $(carousel).parents().addClass("animate"); $(carousel).css({ 'left': -carouselItemWidth }).css('width', '9999px'); $(carousel).find("li:first").before($(carousel).find("li:last")); //if user clicked on next button function goToNext(){ var carouselItemWidth = $(carousel).find("li").outerWidth(); var left_indent = parseInt($(carousel).css('left')) - carouselItemWidth; var Only2 = false; if ($(carousel).find("li").size() == 2){ $(carousel).find("li:first").clone().appendTo(carousel); Only2 = true; } $(carousel).animate({ 'left': left_indent }, 500, function() { $(carousel).find("li:last").after($(carousel).find("li:first")); if (Only2 == true){ $(carousel).find("li:last").remove(); } $(carousel).css({ 'left': -carouselItemWidth }); }); return false; } //if user clicked on next button function goToPrev(){ var carouselItemWidth = $(carousel).find("li").outerWidth(); var left_indent = parseInt($(carousel).css('left')) + carouselItemWidth; $(carousel).animate({ 'left': left_indent }, 500, function() { $(carousel).find("li:first").before($(carousel).find("li:last")); $(carousel).css({ 'left': -carouselItemWidth }); }); return false; } var carouselScroll = setInterval(goToNext, carouselInterval); //if mouse hover, pause the auto rotation, otherwise rotate it $('.mainFeature').hover(function(){ clearInterval(carouselScroll); }, function(){ carouselScroll = setInterval(goToNext, carouselInterval); }); $(prevBtn).click(function(){ goToPrev(); return false; }); $(nextBtn).click(function(){ goToNext(); return false; }); }
URL: http://www.queness.com/post/923/create-a-simple-infinite-carousel-with-jquery