Infinite Carousel Photo Gallery With CSS 3 & jQuery

/ CSS, Javascript, jQuery / by Paul Robinson / 71 Comments
This post was published back on February 26, 2011 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

As I said the original inspiration behind this gallery is now gone, but the idea is still there. The gallery was basically an infinite carousel showing one image in the center with 1 half showing either side. I remember looking at the code used for it & thought there must be a simpler way to do it as it seemed extremely complicated. Then I realized the code was quite old and jQuery has come a long way since then, so here is my version of that photo gallery.

Infinite Carousel Gallery: Concept

The idea seems simple, a carousel of images that you can flip left or right through. The infinite part comes into play when you reach the last image. How? Well, when you do reach the last image the next image you see is the first image again. This let’s you flip through all the images without reaching an abrupt end.

I like the whole illustrate with images thing I’ve had going on in the last tutorial or two, so let’s keep it going. First let’s see what we are going to make, and you can try it out by clicking the demo below that. Just remember you’ll need an up-to-date version of a modern browser to view it at it’s best.

Now that you can see what we are going to be making, and you’ve had a chance to try it out let’s look at browser support.

  • Firefox 3.6 – Works with all features.
  • Chrome 11 – Works with all features.
  • Opera 11 – Works with all features.
  • Safari 5 – Works with all features.
  • Internet Explorer 8 – Animation works, however box shadow & scaling do not.
  • Internet Explorer 9 (RC) – Works with all features.

One small note about Internet Explorer 9. You must use the correct DOCTYPE or it will enter Quirks Mode & things will all go very strange. In HTML 5 you can use the DOCTYPE shown in the demo that’s:

Now that we’ve looked at potential browser problems let’s get onto the code that runs this bad boy. 😉

Infinite Carousel Gallery: HTML

First onto the HTML. I like to try to keep the HTML as simple as possible so bearing that in mind here is what I ended up with.

As normal you would replace the image paths, and the hyperlinks would point to the larger image. You’ll also need to provide a previous & next button although you can feel free to use the ones on the demo page.

A small, but very important, note is that your images must all be the same size. If they aren’t the CSS should auto resize them in proportion, however it looks neater if they are all the same size. It’s also best if they are all portrait images.

Infinite Carousel Gallery: CSS

There is quite a lot of CSS for this gallery, and a lot of it is needed for it to work properly. Let’s take a look and I’ll highlight the important lines.

First we need to look at some very important numbers that need to be set in the CSS. Unfortunately this is where a bit of complicated Maths comes into play. I’ll try to keep it as simple as possible though.

  • #photos_inner > width • Width of 1 list item (img + border) + left & right margin X 2
  • #photos_ul > left • (1 list item + left & right margin) + (half 1 list item + left margin)
  • #photos_ul li > width • width of 1 image + left & right borders
  • #photos_ul li img > width • The width of your images.

Those are the important sums that must be worked out correctly. If they aren’t you’ll probably find your animation won’t work & things will look a bit… Strange.

Here is a list of the other important parts that you probably won’t have to change, but are needed by jQuery to work properly.

  • #photos_inner > overflow • Hidden
  • #photos_ul > position • Relative
  • #photos_ul > list-style-type • none
  • #photos_ul > width • Must be nearly infinite 9999px is near enough
  • #photos_ul li > margin • Personal choice, but will help determine the values of the sums above
  • #photos_ul li img > border • Personal choice, but will partly determine the list item width

Everything else in the CSS is to help make it look nice, and the CSS 3 rules like box shadow & transform are not needed but when viewed in a browser that supports them it add that little bit of extra spice.

Infinite Carousel Gallery: jQuery

Now for the meaty bit. The jQuery code. This can get a little complicated so my sister over at Lisa Marie Art & Illustration has kindly created some information graphics to help out with the explanation.

First though here is the code in it’s entirety.

First a very important note. I animate the scale property here with jQuery, this is not natively available through jQuery and you will need to download the jQuery CSS Transform patch and the jQuery Animate for Rotate & Scale patch. You will also need to attach them after jQuery, and in that order. Huge thanks to Zachstronaut for making those patches.

Right, now let’s go through all this code piece by piece. I’ll ignore the DOM ready as it’s the same for most jQuery code.

This variable is one that could possibly need changing depending on how you are using the gallery. The only variable here is the path to the UL element containing the images. This can be customized freely. I have tried my best to make the code so that you will only need to change this single line if your UL has a different ID.

The first variable here stores your original left offset from your CSS. This is needed to make the carousel work properly later during the animation stage.

The second variable is just to help with the next sum. It tells it how many images are visible at one time, this includes the two half images either side. This cannot be changed yet as the code will most likely break due to how the infinite part of the carousel works. I’m working on that though.

The last variable here works out which numbered image will be at the center by taking the number of images visible and dividing it by 2, and rounding it up. This works because an odd number of items halved will always give you the number of the center item if you round the resulting decimal up.

Now comes the actual code. From now on I use the variable set before $car as context to select elements starting from the UL element we stored in the user variables earlier.

First we move the last two list items (images) to the front of the carousel. This is just in case the user presses previous first. This is partly the reason why you can’t increase the number of images displayed & needs to be looked at, but for the moment this is the best I’ve been able to come up with. I would have chained them, but for some reason they don’t work the same way & need to be two separate calls to before.

Next we use our patches to scale all the items down to 75% their original size. We have already done that in the CSS, however that is just to stop the flash before the jQuery has loaded. For some reason the jQuery patch does not recognize that you have already set the scale via CSS, so you must set it again here so we can animate it later.

Now we use the scaling again to scale up our center image back to 100%. This gives a nice circular carousel effect to our gallery by making the image on the left & right smaller than the center image. It’s also a lot easier than saying scale all the images except this one.

Now we can start setting up our click events. First our right button. I’ll skip the click binding since that is the same as normal. Obviously you will need to change the path to your right (and left) buttons if you wish, but that is up to you.

The first line of our click event grabs the outer width of our list item. This is the width of the element plus any border, and/or padding. Adding the true boolean also adds in margin, which is perfect for us.

The next line figures out the new left position for the animation by taking the list item width away from the current left position. Since out left position is negative subtracting from it actually adds to it and pushes our left position further into the negative, moving our list items further left.

Now we check to see if our UL is being animated (to stop crazy clickers from causing problems) and animate it to our new left position. Feel free to customize the animation timing although I think 500ms is nice.

Next in a callback function called when our animation finishes we place the first image in our list at the end of the UL. I’ll explain more with the infographics later but suffice to say it basically creates the infinite carousel effect.

Finally we push the left position back to the original offset. We need to do this since we have removed an item from the front meaning our left position no longer needs to take that item into account. Luckily that makes our original position correct again so we can just use that.

As for these last two lines; The first scales up the right image to 100% as it moves into the center, while the second line scales down the previous center image to 75% as it moves out to the left. How do we find the next and center image? Well we just use the ctr_img variable & jQuery’s :eq() selector.

The code for the left button is nearly the same. The only differences are we add to our left position thereby decreasing our left position. We place the last image before the first one, then reset the left position. Finally we scale the previous image to 100% instead of our next image as we are rotating the carousel the opposite way.

Infinite Carousel Gallery: Infinite Concept Explanation

Now for those that want to understand how the whole infinite part of the carousel works here is a infographics style explanation.

Here you can see how the images are laid out. It shows that when the page is loaded the last two images are actually at the front of the carousel. There are 7 images because that’s how many I used in my original example, but to show that it works with any number the demo shown at the start of this tutorial actually has 13 images.

Pressing right will push all the images to the left. The next image to the right will become the center image & to make sure it will be infinite the first image is moved to the end of the list. Every time you press the right button this happens, hence why you never run out of images to view.

Pressing left will push all the images to the right. The next image to the left will become the center image & again to make sure it will be infinite the last image is moved to the front of the list. Once again it does this on every press of the left button. This creates the infinite effect in the opposite direction.

Infinite Carousel Gallery: Conclusion

It’s been a long tutorial, but that is finally it. Hopefully I’ve explained how this all works to a point where it isn’t confusing. I built it, but even I still have moments where it confuses me simply due to the Maths involved (which I was never very good at).

Please remember that this is a tech demo again. Really though other than the scaling & box shadows in Internet Explorer 8, and below there isn’t anything that should cause older browsers many problems.

As always let me know if you have any comments, suggests, questions, or you just wanna say hey this is cool. 🙂 It’s always nice to hear from you guys & gals.

71 Comments

Author’s gravatar

I absolutely love this – the HTML/CSS makes total sense. However, I’m hung up a little bit on the jQuery.

How would I go about building this into a wordpress site? Any sort of generic directions, or advice, would be greatly appreciated!

Thanks. 🙂

Reply
Author’s gravatar author

Well you’d just attach it as normal but in WP you’d need to use the no conflict version.

That would be

If that isn’t the problem though let me know & if you can provide me with any errors I’ll see if I can help you out.

Author’s gravatar author

Oh, I nearly forgot to say thank you Jason. I’m glad you like it. 🙂

Author’s gravatar

Paul – thanks for the quick reply! I guess my real question here is (and it’s a novice one)…

How do I incorporate the jQuery into my WP theme? I’ve read through some tutorials, but it still seems pretty confusing to me.

Do I drop the jQuery code into the functions.php? Or, am I packaging the code into a .js file and calling it up from my theme somewhere?

I guess I need some ‘dummy’ questions answered, but I certainly want to learn how this works, and would be more than happy to drop a donation if it’s going to be a time-consuming answer.

Either way, I appreciate your help. 🙂

Author’s gravatar author

Oh wow… I’m so sorry I didn’t answer Jason (if you read this). WordPress didn’t let me know about your reply. 🙁

You can include the code many ways. The simplest is the same way you would in a HTML page. Add the code to a JS file, upload it to your theme folder and hard code the script tag into the header.php file of your theme.

The better way (in efficency & cleanlyness terms) is to use wp_enqueue_script() in your header.php file above wp_head(). It would look something like:

That will tell WP to load your script. The first is just a name you specify and must not be the same as a WP JS file listed here:

http://codex.wordpress.org/Function_Reference/wp_enqueue_script

The second is the path using the function get_bloginfo to grab the theme path. Adjust as needed. The third is dependancies, what scripts must be loaded before this one. In this case jQuery must be loaded. Finally a version number, can be anything really.

Hope that helps and again I’m so sorry I didn’t reply soon.

Author’s gravatar

Very cool!
What about a large slideshow where you want the current slide to take up 95% of the viewport, with the next/prev slide to the sides?

Reply
Author’s gravatar author

I haven’t tried it as it’s late, but I would imagine the code would be very similar. I tried to make it so size was figured out on-the-fly by the jQuery.

I’d imagine you would just alter the image & CSS sizes to take up 95% of your screen.

You’d have to alter the pixel based sizes to percentages to get around different screen resolutions (mine is 1920×1080 for example), but it may make things slightly difficult due to problems I’ve had with jQuery animations and percentages. If you can get around that though it should work no problem.

Oh, and thank you. I’m glad you like the overall effect. 🙂

Author’s gravatar

Hmmm…. Great carousel. Love it… but I checked and double-checked and I can’t seem to insert more that 26 photos before the carousel breakdown. Any thoughts on this?

Reply
Author’s gravatar author

Hi,

I’ve never tried that many photos. I’ll give it a try later today & get back to you with what could be wrong. 😉

Author’s gravatar author

I just realized I never got back to you. I’m very sorry.

I tried it with 52 image & all seemed to work fine. What exactly happened when you added 26 in?

Author’s gravatar

hi, i really like this carousel its what i am looking for but i wanted to add links to a certain image so it would jump ahead, but i can’t seem to figure out how to do it can you offer any help

Reply
Author’s gravatar author

Hi Martin,

I’m trying to figure something out for you. I’ll get back to you tomorrow with what I have.

Author’s gravatar author

Hi Martin,

I’ve tried my best to come up with something, but unfortunately due to the way the carousel is made it seems to be very difficult to come up with anything like a navigational pip system like other sliders. It seems to be due to the way the infinite part of the carousel has to be created combined with the fact you can always see half of two images either side of the main one.

I’ll keep at it though & I’ll add it to the post if I come up with anything.

Author’s gravatar

Yes thanks for you help i have now managed to do the same thing with jcarousel,

Author’s gravatar author

Hi Martin,

glad you’ve managed to find something that works for you. Any chance you can post a link so everyone can see it?

Author’s gravatar

A great tutorial, and a fantastic carousel. I am already using it on my site, but I was just wondering if there was a way to make the carousel revolve automatically, say every 5 seconds or something. This would be a great help as I really like the design and features of this, but it would be even better if it could automatically revolve, without the user having to click the nav to make it do so. Thanks in advance

Reply
Author’s gravatar author

Hi James,

it all depends on if you want it to revolve automatically all the time & remove the nav ability or not.

If you want to remove the nav ability then you probably could by taking the code inside one of the click events & placing it in a setInterval instead of the click event.

So something like:

The 5000 on the end is how long between triggers in milliseconds.

Alternatively if you want to keep the nav you could try setting up a setInterval to trigger one of the buttons. So:

The problem is that it will continue while people click the buttons so you could add a piece of code to stop the auto scroll while a visitor is hovered over the nav buttons like this:

Please bare in mind all this code is just off the top of my head, lol. Hopefully it will work for you.

Also thank you for the kind words. I’m very happy you like it. 🙂

Author’s gravatar

Thanks that was just what I was looking for. However, I’m very much new to jQuery, and I couldn’t get this auto revolve code to work. I chose to have it auto revolving, but stopping if the user hovers over the nav.

It is most likely that I have done something wrong.
All of the jQuery code is in an external document, and it all works fine, except for the auto scrolling code. I simply copied out the last piece of code you gave me at the bottom of the page.

Please tell me what I am doing wrong!
Thanks for the speedy reply!

Reply
Author’s gravatar

Sorry I just tried again, and can get it to work auto scrolling, but just can’t get it to stop when the user hovers over the nav.

Here is what I got so far:

Thanks for your help

Reply
Author’s gravatar author

Hmmm. I’m not sure why that isn’t working as there doesn’t seem to be anything wrong.

Are you getting any errors reported by your browser?

Author’s gravatar

No – its working perfectly fine rotating by itself, but like you said it really needs to pause when you hover over the nav. If you still can’t figure it out don’t worry about it.

Reply
Author’s gravatar author

I honestly have no idea why it isn’t working. 🙁

I’ve tested it out & it doesn’t work, but I can’t see any reason for it.

Author’s gravatar

OK, don’t worry about it. Thanks for trying! Thanks for the great slider, tutorial and quick replies!

When the website that I am making with this on it is online, I will post the address here so you can see. Thanks again!

Reply
Author’s gravatar author

Thanks James. Would love to see it. Sorry I wasn’t able to help get the auto rotate working. I’ll keep working on it and add it to the post if I ever get it to work.

Author’s gravatar

For starters great tutorial and carousel this was the most informative information I could find pertaining to resizing the carousel. One question I have though how would I implement more than one of these on the same page? I ask because for our videos page on our website we were wanting a click-able categories that in turn opened up a gallery of images. Those images in turn would essentially be buttons to call our videos from our youtube page. Do I need to write a function for each category? Any help on this would be much appreciated.

Reply
Author’s gravatar author

It may be possible to make it into a jQuery plugin & call one for each gallery you need but I have absolutely no experience with creating jQuery plugins so I’m afraid I have no idea how to do that.

I would try to put something together for you but I’m currently in the middle of work for a client & I don’t have the time. I’m really, really sorry.

Author’s gravatar

It’s alright Paul I’ll keep goofing around with it. Our current video page will work for now since we don’t have enough testimonials to fill the categories anyway. I tried switching things to classes and got unexpected results when hiding one gallery from the page. I’ll try your suggestion of making it into a plugin hopefully I can figure it out. When I get something working I’ll post it here. And since I just read this on my lunch break “Happy Programmers Day”.

Reply
Author’s gravatar author

If I find a few minutes spare I’ll definitely try to make a jQuery plugin out of it. I’ve been meaning to try it out for ages, but just haven’t had the time sadly.

Author’s gravatar

Thanks so much for this awesome slider! I was wondering which DOCTYPE makes it work in IE? I have gotten it to work across all the platforms, even my phone’s browser except IE. It slides but the background doesn’t show nor does it stay within the defined space. Thanks for any ideas you can give me!
Cole

Reply
Author’s gravatar author

Hi,

Glad you like it. 🙂

As mentioned in the tutorial I could only get it to work correctly (only in IE 8 & 9 though) using the HTML 5 Doctype which is backward compatible with most, if not all, browser.

A caveat is that you must have the xmlns="http://www.w3.org/1999/xhtml" inside your HTML tag or it won’t work.

Reply
Author’s gravatar

Thanks Paul!

I’d tried the HTML 5 and all kinds of things and wondered if maybe I’d misunderstood. 🙂 Just wanted to make sure. I’ll go check out where my tag is…maybe that’s the trick. 🙂

Thanks so much for it, getting back to me so quickly and the clear instructions!
Cole

Reply
Author’s gravatar author

No problem.

Take a look at the source code for the demo if you need any sort of reference. You might be able to compare it to your code to see if you have any differences.

Author’s gravatar

Hey, I just wanted to pass this on in case it helps anyone else.

I used your demo and sourced it and finally took my page out of wordpress and created a plain html page in order to track down what was wrong. Or tried to. It still didn’t work. I then tested your demo in my IE9 browser(just opening the demo there) and couldn’t get it to work there either. (I probably should have started with checking your demo in IE but…then I might not have put so much time into it and not kept on looking then to find a solution.)

In searching the net for a hack to make it work I came across a directive hack(there probably is a better way to say that but…it works for my brain 🙂 ) If you stick the following bit directly under the it works in IE! 🙂

I am guessing this means I have something wrong in my pages – I’m still learning – but it was so wonderful to have it work!

Thanks again!!! I love that it works in all the places I wanted.
Cole

Reply
Author’s gravatar author

Do you mean that the demo here on my site didn’t work for you in IE9? If so that’s very odd as it works great for me in IE9, and IE8. Just not IE7.

Author’s gravatar

Hey Paul,

Yep, your demo would not work for me in IE9. I’m really, really glad I didn’t try it there first – I would have given up. I use Firefox but check things in the different browsers. I was willing to just have this work in the newer browsers though. If you click on the developers link in IE9 it will open another window and allow you to try the page in different modes – for some reason it wants to open your demo (and my page without that extra code) in IE7 – which as you said, then does not work. I tried and have been looking to see if there is a way to set the IE browser to just choose to open things in IE9 but haven’t found it. (Assuming that for some reason perhaps my IE browser is set up incorrectly) Instead I found that bit of code on how to tell the IE browser to make sure it opens it correctly.

Is that too long of an answer to your simple question? 🙂
Cole

Reply
Author’s gravatar author

Ahh. So you mean that IE9 is picking the wrong standards mode for you? Mine always uses IE9 with IE9 standards mode when I open the demo, I’m not sure why it would use a different version.

I think there is a Meta tag you got put in you HTML that will force IE to use the latest rendering mode available. Even as far as forcing Chrome frame for IE to be enabled if it’s available, but for the life of me I can’t rememer it.

I have it on my computer somewhere, I’m posting this from a Galaxy Tab, so I’ll see if I can post it a bit later for you.

Author’s gravatar

Yep, that’s what I added – a bit of code that tells IE to use the mode I want it to use. 🙂

Reply
Author’s gravatar

Hi, thanks for the great tutorial! I am a CSS noob, and yet I managed to get the auto-advance version running (with my own images, no less, as much as I enjoy Chuck…). I’ve been trying to decrease the space between the center image and its scaled counterparts to the left and right, and I’m not having much luck. Any suggestions?
Thanks again,
Matt

Reply
Author’s gravatar author

Hi Matt,

Nice job figuring it out, I sometimes find it difficult and I built it, lol.

To alter the margin is a pain, but due to the knock on effect it has you have to alter quite a few things. First you change the margin, let’s say we want to reduce it to 20px left & right instead of 40px. You need to do the following:

  1. Change #photos_ul li margin to margin: 10px 20px;
  2. Now minus the amount we removed from the left margin (20) and the right margin (20) multiplied by 2 from the #photos_container and the #photos_inner width.
  3. Now add the amount removed from margin left (20) + the amount removed from margin right (20) plus the amount removed from margin left again (20) from the left position of #photos_ul. Remember adding to this number makes the number decrease because it is a negative number.

That seemed to work for me. If you get confused the sums to work out the number are next to the CSS in the demo if you view the source code.

Let me know if you have any problems. I’m not brilliant at math so you might have a better time with the sums than I did.

Author’s gravatar

Thanks Paul,
Check it out: http://www.michigan.gov/dnr/0,4570,7-153-10365_58648—,00.html

I had to make the borders dark because most of our users are using IE8 or earlier and without the drop shadow the images appeared frameless. Also, I had to use an iFrame to call the content, as setting up stuff like this in our CMS is nearly impossible. Still, I’m pleased with the result. I will mess around with the math a bit later, possibly when a headache sounds appealing. 😉
Thanks again!
Matt

Reply
Author’s gravatar author

Wow, very impressed. If you can get the pictures to fit the iFrame by altering the border it should look amazing. Okay scratch that, you already have, looks amazing. 🙂

Yeah, unfortunately altering the margin is a headache. I keep meaning to come back & try and add something in to work out the math automatically, but I keep getting buried with work. 🙁

Author’s gravatar

This demo is great, but i have a question… If somenone want to put photos with other width and height what is going on???

Reply
Author’s gravatar author

Hi Stella,

I’m not sure I get what you mean? If you are asking how you use different width & heights for the images, the answer is simple. You don’t. This is a gallery that requires a uniform sizing to your images, as is the case of a fair few galleries.

If you mean how do you change to a different size image to that of the demo, well you follow that maths in the comments on the CSS file. Unfortunately that is the only way to alter it. It could be done with Javascript, but ultimately if someone has JS disabled it will at least stay presentable because the main styling is pre-set in the CSS file.

Author’s gravatar

First of all, this is a great tutorial for every level web programer. But, i am trying to have infinite carousel more than one dynamically in the same page. For example, in real estate site there are ads and inside of every ad div there should be infinite carousel photo gallery, so i tried to combine ur code with php like,

while($row = mysql_fetch_array($result))
{
.
.
.
}

but it did not work like this, so please can you help me?

Reply
Author’s gravatar author

Hi Ozan,

I think your code may have gotten messed up by WordPress. Any chance you can repost it on pastebin or something similar?

Author’s gravatar

I only have one question.. how to set up the jQuerry or call it? Should I save it on another file and what is the file type after saving? Sorry for the newbie question.

Reply
Author’s gravatar author

Hi Josh,

you can do it one of two ways. Place it in script tags like this:

Or you can save it in a separate file which would have the file extension .js then link it like this.

Both of these methods must be done inside the head tag of your HTML file.

Hopefully that helps. Let me know if you need any further help.

Author’s gravatar

Thank you so much for this. I was looking for something different to display picture. It worked great for me. I used it with an iframe. I also worked up a quick spreadsheet to do the math. So great of you to share!

Reply
Author’s gravatar author

Hi Joan,

Thanks so much, I’m glad you were able to use it. 🙂

Never thought about using a spreadsheet to work out the Math, I used my sister who was always better at that stuff than me. 😉

Older Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more