Easy jQuery Carousel

By | February 21, 2011

Ok, so we’ve all seen them sliding across our screen, fading in and out, shaking, twisting, shouting look at me, I’m clever.

They probably started out as an animated gif of javascript if you were clever, went to being Flash, when flash was in fashion (Macromedia 8 or CS3) and all the cool kids or so called Gurus were using it. Now it’s turned full circle and we’re back in realms of Javascript with one of the many libraries, jQuery, dojo, mootools, prototype all doing multiple versions.

Image rotation, slideshow, carousel they have many different names and many guises but they all all do the same thing, show lots of content in the same area. Great when all you have work with is 1024 x 768 ( worst case scenario as my boss says like a mantra for the web designer).

So how do we do it?

Get a plugin I hear you cry!!!

Yes admitted you could get a plugin and there are a few good ones out there. jQuery Cycle for one which does just about anything that you want to do. There’s also a great little script called Tinyslider.js that is easy to implement, supports pagination and as the name suggests is…..well……tiny.

But what if Cycle is too big load hit and what if Tinyslider doesn’t do what you want if you want a more customized slider. What if the internet broke and you could only get on my blog or look at web designer magazine (which is where I borrowed the idea from for this).

Then you might say…

How can I make an infinate slider with just 5 lines of code (and a whole jQuery library to support it but you had that anyway because everyone does!!? Don’t they?)

First we need to set up the HTML and CSS.

So here we have a containing

with our list of images inside.

#carousel {
		width: 480px;
		overflow:hidden;
	}

	#carousel ul {
		width: 1920px;
		padding: 0;
		margin: 0;
	}

	#carousel ul li {
		width:480px;
		text-align: center;
		height: 280px;
		list-style: none;
		float:	left;
	}

First we put a property of overflow:hidden on the container so all the images apart from the first one are hidden.
Next we make the list wide enough to encompass all the images
Then we float all the images left so our list is just one long list of images take away the list style so theres no ugly bullet point.

So the Pseudo Javascript Code

I like to do this so I know what I’m trying to achieve. then I can work through the code one problem at a time.

So here goes.

when page is loaded
wait 5 seconds
move the list of images left by the individual images width
remove image from list
add it to the end of the list
then start the cycle again

So hopefully this is self explanatory but above is what we are going to do.

Actual Code

So before we start we have to bring in the jQuery library. You can download this library and host it locally but I like to just link to it from the repository

Next we go back to our pseudo code, we want to wait till the document loads so that we know all the elements on the page that we are going to manipulate are loaded. If they are not there we may get an error.

$(document).ready(function(){
// code goes here
	});

jQuery is great because it gives us this easy piece of code to check when the document is loaded. Now all we need to do is put the rest of our code in the middle of this.

$(document).ready(function(){
            var t = setInterval(function_code_goes_here,5000);
	});

So the above code now waits for 5 seconds or sets an interval of 5 seconds (5000 milliseconds) then executes the code at the beginning of the brackets. So Lets put that in now.

$(document).ready(function(){
	// Set the interval to be 5 seconds
	var t = setInterval(function(){
		$("#carousel ul").animate({marginLeft:-480},1000,more_code_here)
	},5000);
});

Now we’ve added the jQuery animate function to here we are moving the list within the carousel div 480px to the left (thats what the minus sign is for, if it was to the right it would just be 480), it’s going to take 1 second (1000 milliseconds) to move the list and then when you’ve finished the animation execute the next bit of code.

$(document).ready(function(){
	// Set the interval to be 5 seconds
	var t = setInterval(function(){
		$("#carousel ul").animate({marginLeft:-480},1000,function(){
			$(this).find("li:last").after($(this).find("li:first"));
			$(this).css({marginLeft:0});
		})
	},5000);
});

The final piece of code finds the first and last li element within the list and places the first one after the last. As you can see in the code it doesn’t read like this so I will explain it from right to left to hopefully make it easier to understand whats going on.
Find the last li and place after this element the first li. Hope that makes sense… it does in my head.
Then lastly change the left margin back to 0 (because it was at -480px remember?).

Thats it well done.

Click here for the full demo of the jQuery Slider. Or here for Code Snippets.

26 thoughts on “Easy jQuery Carousel

  1. Pingback: Tweets that mention Easy jQuery Carousel -- Topsy.com

  2. Vinayak Phal

    Its really nice for me, as I’m a beginner in jQuery.
    Its a really good explained tutorial.
    I liked your Pseudo code technique of explaining.

    Thanks!!

    Reply
    1. Matt Walker Post author

      Yeah of course. That would be great. Send me a link through to the site so I can have a look too. Glad to be of help.

      Reply
  3. matt l

    Hi guys,

    Really nice tutorial. In real word if you change the dimentions a bit it kind of “jumps” … animation isn’t smooth.
    Any Ideas ?

    Reply
    1. Matt Walker Post author

      Hi Matt

      Could you give me link to the page and I’ll have a look.

      Cheers

      Matt

      Reply
  4. Mark

    Thanks heaps for this code extremely simple, yet elegant solution. I tried the other Carousel plugins but spent far too much time trying to customise slash alter the buggy code. Just couldn’t get them too work. I may as well of written my own version in that time! Here goes.

    Reply
  5. shoppersisane

    Hello, may i know where to put

    #carousel {
    width: 480px;
    overflow:hidden;
    }

    and

    $(document).ready(function(){
    // Set the interval to be 5 seconds
    var t = setInterval(function(){
    $(“#carousel ul”).animate({marginLeft:-480},1000,function(){
    $(this).find(“li:last”).after($(this).find(“li:first”));
    $(this).css({marginLeft:0});
    })
    },5000);
    });

    ?

    Is it in a seperate or the body or what?

    Reply
  6. Gisela

    I am trying to use the carrousel, but when I changed the size 1000px x 350px, the second picture take time to come. Do you know what can I do? Thanks

    Reply
  7. Parveen

    if we have 9 images(3*3) in a carousel and we want to slide 3 images at a time then what would be the code?

    Reply
  8. Shweta

    Yes,Even i am looking for similar behavior wherein i can slide 4 images at a time.
    Please suggest the solution.

    Reply
  9. Bernie

    Great post. I’d like to know the necessary code to change the direction so the new slides appear from left to right.

    Thank you!

    Reply
  10. Rakesh

    Great tutorial mate… I’m looking for more tutorial such as:

    1: LightBox
    2: Pop Up
    3: Accordion
    4: Sliders and so on…

    Please provide me a link…

    Thanks
    Rakesh

    Reply
  11. mica

    Im plannig to make my first working website for my portfolio. thanks for this tutorial.. well explained for beginner in jquery.. Excited to try this one! hope for response if i hav some question. Thanks sir!

    Reply
  12. Karine

    Thank you so much to share it!!! It’s so easy whereas I’m always fighting with Jquery! 😉

    Reply
  13. Saravanan

    Really gr8 tuts Matt Walker….its useful for beginner to attend any jquery related jobs interview. Including me also 🙂

    Reply
  14. Jim Gray

    Great tutorial, thank you for putting this up. I’m just beginning to learn HTML and CSS so I haven’t gotten as far as learning Javascript of jQuery yet and was still able to get this working from your post. Would there be a way to add a pause button to this? Any help or just a point in the right direction would be appreciated. Thanks again!

    Reply
  15. Ariel

    Thank you so much for this super simple carousel tutorial! I noticed that the carousel has a bit of a noticeable effect on computer performance, especially as the images get bigger and more numerous, but other than that, this really is quite ingenious 🙂

    Reply
  16. Rama Krishna

    Its really nice and easy to understand.
    can we add a feature like,
    1). pagination i.e to show the image number at the bottom.
    2). its auto, can we make it move on mouse slide?
    Help me out with these added features…

    Thanks in advance.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *