Create a Simple Infinite Carousel with jQuery

Written by Kevin Liew on 28 Oct 2009
280,647 Views • Tutorials

Introduction

Finally, I have times for this carousel script. I always think that it's hard to figure it out, but thanks to a tutorial - Making a jQuery Infinite Carousel with nice features from tutsvalley. I learnt something new from there. So, yes, I modify the code and make it into something I want, and hopefully this is what you want as well :)

1. HTML

Alright, We have a main wrapper called carousel and inside it, we have two sections - buttons and slides. I have styled the previous and next links to two arrows with mouseover effect. The rest is pretty basic.

<div id="carousel">
	<div id="buttons">
		<a href="#" id="prev">prev</a>
		<a href="#" id="next">next</a>
		<div class="clear"></div>
	</div>
	
	<div class="clear"></div>

	<div id="slides"> 
		<ul>
			<li><img data-src="slide1.gif" width="240" height="240" alt="Slide 1"/></li>
			<li><img data-src="slide2.gif" width="240" height="240" alt="Slide 2"/></li>
			<li><img data-src="slide3.gif" width="240" height="240" alt="Slide 3"/></li>
		</ul>
		<div class="clear"></div>
	</div>

</div>

2. CSS

CSS is a little bit complicated. First of all you have to set correct width in #carousal, #slides, #slides ul and also #slides li. So, I break it down and put extra comments, and if you want to change it, I'd recommend you change it from the LI item first, and the following is the sequence:

  • #slides li :
  • #slides ul : the width is the total width of #ul li items
  • #slides : the width and height should be the same with #ul li items
  • #carousel : the width should be slightly bigger than #ul li items, except the height, because it inclde the height of buttons as well.
#carousel {
	width:255px;
	height:290px;	
	margin:0 auto;
}

#slides {
	overflow:hidden;
	/* fix ie overflow issue */
	position:relative;
	width:250px;
	height:250px;
	border:1px solid #ccc;
}

/* remove the list styles, width : item width * total items */	
#slides ul {
	position:relative;
	left:0;
	top:0;
	list-style:none;
	margin:0;
	padding:0;	
	width:750px;			
}

/* width of the item, in this case I put 250x250x gif */
#slides li {
	width:250px;
	height:250px;	
	float:left;
}

#slides li img {
	padding:5px;
}

/* Styling for prev and next buttons */
#buttons {
	padding:0 0 5px 0;	
	float:right;
}

#buttons a {
	display:block; 
	width:31px; 
	height:32px;
	text-indent:-999em;
	float:left;
	outline:0;
}

a#prev {
	background:url(arrow.gif) 0 -31px no-repeat; 
}

a#prev:hover {
	background:url(arrow.gif) 0 0 no-repeat;
}

a#next {
	background:url(arrow.gif) -32px -31px no-repeat; 
}

a#next:hover {
	background:url(arrow.gif) -32px 0 no-repeat;
}

.clear {clear:both}

3. Javascript

There are two new methods we are about to learn. Well, it's something new to me too! After and Before method.

  • After - Insert content after each of the matched elements.
  • Before - Insert content before each of the matched elements.

So, to create an infinite carousel, we need to depend on these two method because we need:

  • If the user clicked on previous button, we need to move the last item to the front of the first item
  • If the user clicked on next button, we need to move the first item to the back of the last item.

As a result, whenever we clicked on next or previous button, the script will keep moving the item and that make it an infinite carousel. Again, credit to my friend at tutsvalley for this idea, check it out his version of carousel - Making a jQuery Infinite Carousel with nice features

And also, our very cheapskate but absolutely effective method of rotating the slide - using click() function to click next link and set a timer for it :)

$(document).ready(function() {

	//rotation speed and timer
	var speed = 5000;
	var run = setInterval('rotate()', speed);	
	
	//grab the width and calculate left value
	var item_width = $('#slides li').outerWidth(); 
	var left_value = item_width * (-1); 
        
    //move the last item before first item, just in case user click prev button
	$('#slides li:first').before($('#slides li:last'));
	
	//set the default item to the correct position 
	$('#slides ul').css({'left' : left_value});

    //if user clicked on prev button
	$('#prev').click(function() {

		//get the right position            
		var left_indent = parseInt($('#slides ul').css('left')) + item_width;

		//slide the item            
		$('#slides ul').animate({'left' : left_indent}, 200,function(){    

            //move the last item and put it as first item            	
			$('#slides li:first').before($('#slides li:last'));           

			//set the default item to correct position
			$('#slides ul').css({'left' : left_value});
		
		});

		//cancel the link behavior            
		return false;
            
	});

 
    //if user clicked on next button
	$('#next').click(function() {
		
		//get the right position
		var left_indent = parseInt($('#slides ul').css('left')) - item_width;
		
		//slide the item
		$('#slides ul').animate({'left' : left_indent}, 200, function () {
            
            //move the first item and put it as last item
			$('#slides li:last').after($('#slides li:first'));                 	
			
			//set the default item to correct position
			$('#slides ul').css({'left' : left_value});
		
		});
		         
		//cancel the link behavior
		return false;
		
	});        
	
	//if mouse hover, pause the auto rotation, otherwise rotate it
	$('#slides').hover(
		
		function() {
			clearInterval(run);
		}, 
		function() {
			run = setInterval('rotate()', speed);	
		}
	); 
        
});

//a simple function to click next link
//a timer will call this function, and the rotation will begin :)  
function rotate() {
	$('#next').click();
}

Conclusion

Like this tutorials? You can express your gratitude by visiting my sponsors on the sidebar, bookmark it and help me to spread this tutorial to our friends! :) Thanks!

Demo Download
Join the discussion

Comments will be moderated and rel="nofollow" will be added to all links. You can wrap your coding with [code][/code] to make use of built-in syntax highlighter.

79 comments
Nasir 13 years ago
Hello fellow developers, nice carousel. Although it wasn't displaying correctly...so I amended this line:

var left_value = item_width * (-1);

TO

var left_value = item_width * (0);

Now it's working as it should, thanks
Reply
Tony 12 years ago
Thx Nasir, it works fine! This display bug appears when i use only 2 slides.
Reply
Tintin 13 years ago
Hi
I would like to try this out. But not really sure how to integrate this on my website. Do you have a step-by-step instructions for this?
Thank you would appreciate it
Reply
Susana 13 years ago
Hi! nice carousel! It's the only one I've tried that actually works for me! Now, I would like to know how to put two or more carousels in the same page, Is that possible? what part of the code should I change?
Thanks a lot.
Reply
Kevin Liew Admin 13 years ago
Yes, it's possible, but you will need to do some modification. You need to specify an ID for all the carousels, and then you mod the script $('#slides ul') to $('#carousel1 #slides ul'). I think it should work.
Reply
Klarise 13 years ago
Hey there Kevin, thanks for the tutorial. Very nice simple carousel to give basic understanding of slider looping... I am trying to implement this infinite loop idea into my slider which is a bit complicated (besides the arrows it has thumbs you can click on) and it was not originally made to loop continuously, but when I try to use this on it's own it's working well...
Reply
Jake 13 years ago
hi kevin,

How can I stop the "auto rotate" on your code? I love the code thanks Man.
Reply
Kevin Liew Admin 13 years ago
Hi Jake, if you look at the mouse hover section of the code, it has a code to pause the carousel and also, a code to start the carousel again. What you need to do is, you can click a button and assign click jquery event, then put in this code:

To stop the carousel:

clearInterval(run);

To play the caousel:

run = setInterval('rotate()', speed);

it should work. :)
Reply
Panda 13 years ago
Im trying to impliment this on a site but want it to be vertical. Im sure its just modifying couple of the variables and such but I dont know which/ where to begin any help is greatly appreciated. thanks!
Reply
Aubricus 13 years ago
Can you provide source code that hasn't been compressed? Makes it pretty difficult to work with. Thanks for the tutorial. Best wishes.
Reply
Kevin Liew Admin 13 years ago
it's not compressed.
Reply
ZIBI 13 years ago
How can I stop the "auto rotate" on your code? and I would like to know how to put two or more carousels in the same page.Sorry for my language - I stil learn. I seen answer on that. But please expand that if its possible. I dont know realy how to do it. Please for help...:)
And its first tutorials, I understand and working.
Reply
Rudys 13 years ago
Hi kevin!
nice work.
Mm. how to add a caption below?
Thanks .)
Reply
kamal 13 years ago
i can't to repeat this carsoul in my page html i need to help plz
Reply
mark 12 years ago
I needed to create a random starting point, and did a bunch of dumb stuff before the simple answer came to me.
So, I just added a random # for loop to interate over the push pop method you use:
var x = (Math.floor(Math.random()*24) + 1);
for (i=0;i<=x;i++){
$('#slides li:first').before($('#slides li:last'));
}
And to hide the jump at the beginning, i just put in a blank slide as the first one - having failed to get css display or show / hide to do the job. Thank you for the lesson in jquery!
Reply
Matt 12 years ago
anybody know how to set a default starting point?
Reply
Joe G 12 years ago
Hi Kevin,

Great code! Thank you! I was wondering if there was any way to setup a page where for example you had a small left column (300 pixels) and then a second column that extends the width of the browser. Then insert the carousel code in the area that resizes and have the images slide and also fill the entire area and resize in the browser? Is this possible?

thank you!
Reply
Kevin Liew Admin 12 years ago
This carousel wasn't display for dynamic width. However, I can recommend on to you:
http://caroufredsel.frebsite.nl/
Reply