Create a Simple Infinite Carousel with jQuery

Create a Simple Infinite Carousel with jQuery


Create a Simple Infinite Carousel with jQuery

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 src="slide1.gif" width="240" height="240" alt="Slide 1"/></li>
			<li><img src="slide2.gif" width="240" height="240" alt="Slide 2"/></li>
			<li><img 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!

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

71 comments

saurabh shah
Thu, 29th October 2009
N ice Carousel.. Simple and very clean ... Reply
Boba
Thu, 29th October 2009
It\'s great :)

And thanks for mentioning my carousel :) Reply
Rajiv gopalha
Thu, 29th October 2009
It seems to me quite complicated, but I try to understand..visit website science and technology http://roxeva.blogspot.com Reply
Sanid
Fri, 30th October 2009
Nice one thanks ... will try to get this working for wordpress :) Reply
sukhchander
Mon, 2nd November 2009
an infinite carousel shouldn\'t need controls, right? it just loops.

i created a much simpler slideshow on my own page: http://bit.ly/1AqLSh

appreciate the feedback Reply
clippingimages
Sun, 8th November 2009
Nice and well defined jqueries. Thanks for sharing this nice post. Reply
planeth
Fri, 18th December 2009
Thanks for this usefull code .
I tweaked it a bit, to make it a little more accessible.
inside the css .carousel_inner overflow is set to auto to prevent people without javascript not seeing the other images,
and inside the script the overflow property is set to hidden
$(\'.carousel_inner \').css({\'overflow\' : \'hidden\'});
And i used the click function to trigger the
#left_scroll and #right_scroll
$(\"#left_scroll\").click(function() {slide(\'left\');
return false;});
$(\"#right_scroll\").click(function() {slide(\'right\');
return false;}); Reply
Faiz
Sat, 16th January 2010
Hi nice work.

Can i use it to create wordpress plugin and submit to wordpress .org for public use.

If you have any doubt please contact me via mail

Thanks
Reply
kevin Admin
Sat, 16th January 2010
hi faiz, it's free to use :) Reply
Vinu
Sun, 24th January 2010
Hi Kevin,

Great work! It looks real good :) Is it possible to make this carousel a non-circular one? How do we do it?

TIA. Reply
Ruben_H
Sat, 6th March 2010
Hi, the carousel looks very nice, but it has problems with Chrome and Safari(Win ed.).

It seems that removing the setting of the default positions helps some, but still then the carousel doesn't revolve more than once.

I hope you have some ideas about a solution. Reply
David Karlin
Thu, 22nd April 2010
Great piece of code, I'll be using something very much based on it. Thanks very much.

The Chrome problem is this: parseInt won't accept a value like "300px" - it gives the answer NaN. I fixed this by creating the following:

function myParseInt(str){
var px=str.indexOf("px");
return px>0 ? parseInt(str.substr(0,px)) : parseInt(str);
}

Hope this helps! Reply
Help me
Thu, 30th September 2010
Does anyone have any hints on how to go about adding a pager, with links that go to each specific slide? Reply
Nasir
Wed, 3rd November 2010
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
Mon, 26th December 2011
Thx Nasir, it works fine! This display bug appears when i use only 2 slides. Reply
Tintin
Wed, 15th December 2010
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
Fri, 14th January 2011
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
Sun, 16th January 2011
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
Thu, 10th February 2011
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
Fri, 4th March 2011
hi kevin,

How can I stop the "auto rotate" on your code? I love the code thanks Man. Reply
Kevin Liew Admin
Sun, 6th March 2011
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
Wed, 6th April 2011
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
Fri, 6th May 2011
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
Mon, 9th May 2011
it's not compressed. Reply
ZIBI
Mon, 23rd May 2011
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
Sat, 16th July 2011
Hi kevin!
nice work.
Mm. how to add a caption below?
Thanks .) Reply
kamal
Mon, 26th September 2011
i can't to repeat this carsoul in my page html i need to help plz
Reply
mark
Sat, 15th October 2011
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
Fri, 2nd December 2011
anybody know how to set a default starting point? Reply
Joe G
Sun, 4th December 2011
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
Mon, 5th December 2011
This carousel wasn't display for dynamic width. However, I can recommend on to you:
http://caroufredsel.frebsite.nl/ Reply
Janice
Fri, 9th December 2011
Hi, this is a great simple code that actually works with clear directions. The other carousels are so hard to add. My question was: how do I make the slides go up/down (vertical direction) instead of left/right?
Thank you. Reply
JC
Fri, 9th December 2011
How do you slow down the actual sliding movement. I understand the time between slides, but actually make them move slower? Reply
Kevin Liew Admin
Tue, 20th December 2011
Line 47: $('#slides ul').animate({'left' : left_indent}, 200...

change 200 to larger number. (in millisecond) Reply
Dave
Wed, 14th December 2011
Does anybody know how to slow down actual animation speed? And how do you slide things in up/down, instead of left/right? Reply
Kevin Liew Admin
Tue, 20th December 2011
You can set it in js script:
//rotation speed and timer
var speed = 5000;

for up/down, you will require fair a bit of changes. It's commented in the js script you can go through and change left to top. Reply
Paul
Fri, 27th January 2012
Hi, i have recently come across this article which has helped me alot in creating what i need.

I have modified the code slighly (taken out some things)

All works fine but i got stuck on how i was able to target a specific slide based on a #

i have popped it all up on JS fiddle to exppalin a little more: http://jsfiddle.net/ZkeJf/3/

Basically when i user clicks link 2 it needs to show the 2nd slide etc etc Reply
Michaela
Fri, 27th January 2012
Hey Kevin,

Thanks for the code! I got it to work with my images in a sample webpage. I am having trouble dropping it into the right place on my website though. It's designed like an old website in tables rather than div tags. ... any help??

Thanks, Michaela Reply
Kevin Liew Admin
Mon, 30th January 2012
I think it's pretty straight forward than div layout. Kinda hard to explain, would you able to show me your site? Reply
ronny
Mon, 20th February 2012
hi kevin, thanks for the code. i'ts almost what i was looking for, but i miss the key arrow function. is it hard to implement? have no clue of javascript. Reply
Kevin Liew Admin
Thu, 23rd February 2012
This tutorial already have arrow function. Prev and next buttons, is that what you want? Reply
kobe
Thu, 8th March 2012
hi kevin, thanks for the code! i've been looking everywhere for a simple one and this is the first one i've gotten to work. i do have a question though, is there a way to put the buttons next to the slides instead of above them? when i try and move them by adding padding it moves the slides down with them. thanks! Reply
Kevin Liew Admin
Thu, 8th March 2012
Hi Kobe, yes, you definitely able to do that.

#carousel put position:relative

Then you can set position:absolute for these two so you can move them around.
<a href="#" id="prev">prev</a>
<a href="#" id="next">next</a>
Reply
Dhanesh S.R
Mon, 19th March 2012
Hi Kevin,
Very nice carousel, pretty good and lightweight.
BTW, I've a doubt how can we stop the infinite loop??
When the list ends, the next button need to disable. Do u have any quick tips for me to do this?
thanks
dhanesh Reply
Sumawigena
Mon, 26th March 2012
Hi, Thank you this is what i was looking for :) Reply
Marc
Wed, 25th April 2012
Great post! I've tried several slideshows but this one should be the best however I couldn't get to work. Even I copied and pasted the js code but to no avail. What am I doing wrong that it will not create a carousel slideshow?

Thanks Reply
Alvaro
Tue, 5th June 2012
Hi!!
Is it possible to list all elements of the carousel and access one particular? Reply
Paul
Thu, 7th June 2012
Great tutorial! I've written a similar one which is a little less complex yet still works quite well.

I'd appreciate any feedback & hope it's handy: http://paulmason.nam e/item/simple-jquery-carousel-slider-tutorial Reply
Dan
Wed, 13th June 2012
Hi Kevin! I was trying to use two of your carousels in one page, but i wasn't hable to do it, I read you comment about it, but i couldn't get it. If you can explain for us a bit more, please :D Reply
Paul
Sun, 1st July 2012
Just wondering what I can edit to make this compatible with multiple image sizes, or if this is at all possible with this method? I tried changing the width and height in the CSS to "max-", but this did not work, and I assume the issue is with the item_width variable using outerWidth(), as this seems to only get the width of the first element in the list. Any help would be appreciated - I am completely new to javascript and pretty new to programming in general. Reply
ahmad badpey
Tue, 3rd July 2012
thanks a lot Reply
avriqq
Thu, 5th July 2012
Thanks, nice carousel.. this is work :) Reply
Myllena nascimento
Mon, 16th July 2012
Eu queria fazer fã club do carrossel Reply
mon
Thu, 19th July 2012
how can i use this with 2 or more display???? plese help :D thank Reply
Srinivas Senapati
Thu, 9th August 2012
Its awesome, I m looking for this come from past I am using plugins but I want write in code without plug in I am very Impressive many thanks Reply
Biscotte1804
Thu, 11th October 2012
Hello Kevin,

Thank you for this great feature.
It has been pretty useful for the web page i designed this summer that is finally online at http://www.promega.com/b/fr/produits/workflowRNA.html
The only thing i'm missing is dynamic height. for the first carousel page. Reply
sandeep
Mon, 15th October 2012
Thanks a lot !!! Reply
Mark
Fri, 19th October 2012
Thank you for the simple code and clear instructions. An excellent starting point! Reply
Emma
Sun, 25th November 2012
I wanted my images to be 500px wide, but I couldn't make it work- would you mind explaining which bits I have to change? The images vanished completely!
Thanks,
Emma Reply
David
Tue, 18th December 2012
Hi, great script, do you know how to change it so that three slides are displayed at once?
Thanks Reply
Jeremy
Thu, 20th December 2012
Hi,

Nice and simple. But if there's only 2 items, the carousel blinks when the element is inserted into the DOM. I've tried playing with the code, but can't get it to smoothely copy the element and then scroll to it.

Any ideas?

Many thanks Reply
Nathalia
Tue, 7th January 2014
Hi!
I had the same problem, looks like the size of the ul sets the quantity of elements to show, so i did this:

var item_width = $('#carrusel ul li').outerWidth();
// how many li are:
var items_cant = $("#carrusel ul > li").length;
// then multiply them:
var new_width = item_width * items_cant;
// and then use it to set the new width:
$('#carrusel ul').css({'width' : new_width});


(more than a year later...) Reply
Arif
Tue, 25th December 2012
It is a good example explaining each and every step simply but professionally.It's really useful for me to create carousel confidently.Thanks a lot for this tutorial.Good luck. Reply
Nirmal
Tue, 19th February 2013
Did any one try implementing pagination on this? Any kind help would be appreciated. Thanks! Reply
Sam
Mon, 6th May 2013
i want show my first li element and then click on next.
as per your code.
the second li element shows first on page load.
how can i do that. Reply
anton
Mon, 1st July 2013
It wold be great if you implement this for example of vertical infinite scroll to.

Thanks for easy to understand example. Reply
Travis
Tue, 2nd July 2013
I was hoping you have an explanation or an idea on how to show all three slides at the same time..? I tried messing around with it but no luck. any help would be much appreciated thank you. Reply
Tania
Fri, 9th August 2013
Thank you for this tutorial. I've read some tutorials about carousel. I hope I can learn it from this one too. Reply
Ursula
Tue, 3rd September 2013
Hello, I just follow this tutorial:
http://www.queness.com/post/923/create-a-simple-infinite-carousel-with-jquery

Is a great tutorial, but i have one question, and I hope you could answer me.

Since i don't want next and prev buttons i try to change this line:

function rotate() {
$('#next').click();
}

to directly the function, this way:

function rotate(){
//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});

}

but nothing works without the click event, and I don't undertand why, (i try many different ways to do it, but no one withoutt the click worked)

I will be so pleased if you could explain me why....

regards Reply
Vinicius
Thu, 21st November 2013
Hey Kevin!

Thanks for the tutorial!
Would like to know if it's possible to add a second slider on the same page?
I've tried, but couldn't manage to do it!
the code I've added to my website is:
<code>
$(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','#slides_2 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', '#slides_2 li:first').before($('#slides li:last', '#slides_2 li:last'));

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

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

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

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

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

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

});

//cancel the link behavior
return false;

});


//if user clicked on next button
$('#next', '#next_2').click(function() {

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

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

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

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

});

//cancel the link behavior
return false;

});

//if mouse hover, pause the auto rotation, otherwise rotate it
$('#slides', '#slides_2').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', '#next_2').click();
}
</code>
thanks! Reply
Jonathan
Mon, 2nd December 2013
cool script! direct and simple! I would like to ask if it is possible to tweak it so it can jump to a specific egg(slide) of the banner? I am facing difficulties in making it dynamic in that sense. A tip from you would be great. Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement