jquery carousel


/ Published in: jQuery
Save to your folder(s)

parameters:

ul containing carousel,
next btn
prev btn


Copy this code and paste it in your HTML
  1. /* carousel */
  2. function carouselFunc(carousel,nextBtn,prevBtn) {
  3.  
  4. //passed variables
  5. var carousel = carousel;
  6. var nextBtn = nextBtn;
  7. var prevBtn = prevBtn;
  8. var carouselInterval = 5000;
  9.  
  10.  
  11. var carouselId = $(carousel).attr("id");
  12. var carouselItemWidth = $(carousel).find("li:first").outerWidth();
  13.  
  14. $(carousel).parents().addClass("animate");
  15. $(carousel).css({ 'left': -carouselItemWidth }).css('width', '9999px');
  16. $(carousel).find("li:first").before($(carousel).find("li:last"));
  17.  
  18. //if user clicked on next button
  19. function goToNext(){
  20. var carouselItemWidth = $(carousel).find("li").outerWidth();
  21. var left_indent = parseInt($(carousel).css('left')) - carouselItemWidth;
  22. var Only2 = false;
  23.  
  24. if ($(carousel).find("li").size() == 2){
  25. $(carousel).find("li:first").clone().appendTo(carousel);
  26. Only2 = true;
  27. }
  28.  
  29. $(carousel).animate({ 'left': left_indent }, 500, function() {
  30. $(carousel).find("li:last").after($(carousel).find("li:first"));
  31. if (Only2 == true){
  32. $(carousel).find("li:last").remove();
  33. }
  34. $(carousel).css({ 'left': -carouselItemWidth });
  35. });
  36.  
  37. return false;
  38. }
  39.  
  40. //if user clicked on next button
  41. function goToPrev(){
  42. var carouselItemWidth = $(carousel).find("li").outerWidth();
  43. var left_indent = parseInt($(carousel).css('left')) + carouselItemWidth;
  44. $(carousel).animate({ 'left': left_indent }, 500, function() {
  45. $(carousel).find("li:first").before($(carousel).find("li:last"));
  46. $(carousel).css({ 'left': -carouselItemWidth });
  47. });
  48. return false;
  49. }
  50.  
  51. var carouselScroll = setInterval(goToNext, carouselInterval);
  52. //if mouse hover, pause the auto rotation, otherwise rotate it
  53.  
  54. $('.mainFeature').hover(function(){
  55. clearInterval(carouselScroll);
  56. }, function(){
  57. carouselScroll = setInterval(goToNext, carouselInterval);
  58. });
  59.  
  60. $(prevBtn).click(function(){
  61. goToPrev();
  62. return false;
  63. });
  64. $(nextBtn).click(function(){
  65. goToNext();
  66. return false;
  67. });
  68.  
  69.  
  70. }

URL: http://www.queness.com/post/923/create-a-simple-infinite-carousel-with-jquery

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.