Create your own jQuery Image Slider

I originally posted this article on 15 September 2010. This is an updated version.

This tutorial is for beginners. The method for creating the slider could be done differently, but I feel this way is more simple to understand.

It is important to picture what the HTML and CSS should be doing in order to create the component before actually beginning with the javascript. This way you know exactly what you are working towards. Below is a gif explaining the concept of the slider in terms of HTML and CSS.


Common things that cross my mind before actually jumping into development are:

Where are the hidden elements situated?
Beneath, on top, next to or behind the visible element?
How are they hidden?
Is their display set to none?
Are they outside of the parent element which is set to overflow: hidden?
Are they hidden behind visible element via z-index?

All right, enough of that, let’s get started.


Before we create anything, we should try and get an idea of exactly what we are trying to achieve. I’ve drawn up a quick image slider wireframe.

So let’s turn that into HTML.

<div class="gallery-wrap">
  <div class="gallery clearfix">
    <div class="gallery__item">
      <img src="images/image1.jpg" class="gallery__img" alt="" />
     <div class="gallery__item">
      <img src="images/image2.jpg" class="gallery__img" alt="" />
  <div class="gallery__controls clearfix">
    <div href="#" class="gallery__controls-prev">
      <img src="images/prev.png" alt="" />
    <div href="#" class="gallery__controls-next">
      <img src="images/next.png" alt="" />

.gallery-wrap will be the visible area.
.gallery is the element that contains the list of images.
.gallery__controls contains the next and previous controls.

Generally an image slider would contain more than 2 images but I’ve left out the exact HTML I used in the demo for readability.


.gallery-wrap { margin: 0 auto; overflow: hidden; width: 732px; }
.gallery { position: relative; left: 0; top: 0; }
.gallery__item { float: left; list-style: none; margin-right: 20px; }
.gallery__img { display: block; border: 4px solid #40331b; height: 175px; width: 160px; }

.gallery__controls { margin-top: 10px; }
.gallery__controls-prev { cursor: pointer; float: left; }
.gallery__controls-next { cursor: pointer; float: right; }

The most important thing here is to set .gallery to ‘position: relative‘ and to set .gallery-wrap to ‘overflow: hidden‘. The CSS is quite straight forward.

The jQuery/Javascript

This is where all the fancy tricks take place.

// Only run everything once the page has completely loaded

    // Fancybox specific
        'titleShow'     : false,
        'transitionIn'  : 'elastic',
        'transitionOut' : 'elastic'

    // Set general variables
    // ====================================================================
    var totalWidth = 0;

    // Total width is calculated by looping through each gallery item and
    // adding up each width and storing that in `totalWidth`
        totalWidth = totalWidth + $(this).outerWidth(true);

    // The maxScrollPosition is the furthest point the items should
    // ever scroll to. We always want the viewport to be full of images.
    var maxScrollPosition = totalWidth - $(".gallery-wrap").outerWidth();

    // This is the core function that animates to the target item
    // ====================================================================
    function toGalleryItem($targetItem){
        // Make sure the target item exists, otherwise do nothing

            // The new position is just to the left of the targetItem
            var newPosition = $targetItem.position().left;

            // If the new position isn't greater than the maximum width
            if(newPosition <= maxScrollPosition){

                // Add active class to the target item

                // Remove the Active class from all other items

                // Animate .gallery element to the correct left position.
                    left : - newPosition
            } else {
                // Animate .gallery element to the correct left position.
                    left : - maxScrollPosition

    // Basic HTML manipulation
    // ====================================================================
    // Set the gallery width to the totalWidth. This allows all items to
    // be on one line.

    // Add active class to the first gallery item

    // When the prev button is clicked
    // ====================================================================
        // Set target item to the item before the active item
        var $targetItem = $(".gallery__item--active").prev();

    // When the next button is clicked
    // ====================================================================
        // Set target item to the item after the active item
        var $targetItem = $(".gallery__item--active").next();

I have heavily commented the above code. All lines beginning with // are comment lines.

To recap, the following was done:

  • Only run everything once the window (page) loads.
  • Calculate the total width of all the images.
  • Calculate the maximum scroll position. This is the total images width subtract the viewport (.gallery) width.
  • Create the toGalleryItem function. This function will scroll to any item we desire.
    • If the target item exists, continue. Otherwise there is nothing left to run.
    • The new position is the left position of the slide/image, relative to it’s container .gallery.
    • If the new position is less than or equal to the maximum scroll position, toggle active classes accordingly and animate to the new left position.
    • Otherwise animate to the maximum scroll position.
  • Set slide container (.gallery) width to the sum of all the images width.
  • Set the first image as active.
  • When the previous button is clicked, go to the previous slide/image.
  • When the next button is clicked, go to the next slide/image.

I will break down the javascript into 2 parts.
I’m going to break the above up into 2 parts. Part explaining the variable declarations and part 2 explaining the rest of the jQuery/javascript.

Summary of javascript/jQuery methods used:


I’ve written an article explaining the various jQuery each methodsa>.

totalWidth = totalWidth + $(this).outerWidth(true);

function toGalleryItem($targetItem)

A function is a bit of javascript that can be run just by calling the function name. Essentially it’s a shortcut. Functions can be made dynamic by allowing the user to pass in variables or parameters such as $targetItem


I’ve written an article about the if statement you may want to have a look at.

addClass and removeClass

These are self explanetory jQuery functions.


This is a magic jQuery function that allows you to animate a wide range of CSS properties.

That’s about it! I hope you’ve found this tutorial useful.

If you have any questions or comments, feel free to leave a comment below.

Any questions or comments?

  1. claus says:

    Hi Jamy

    Some great stuff you got made there, just what I needed.
    But there is one thing i’m curious about. Is it possible to have it so the pictures don’t have to be squashed into the preset width?
    I can see that dictates the movement of the pictures, but what if I just want the pictures to load up in the preset hight and auto ratio the width and then when clicking the button it moves the gallery to the side, i’m not concerned about the pictures being a little covered or not just as long as it moves to the far end and shows the full image on either end.. is that possible with your script with a few modifications?

    1. Jamy Golden says:

      You mean, would it work if the width was set to a ratio such as 100% or 50%?

      Yeah, it definitely would. All you need to do to achieve that is to set the #gallery’s width to 100%, or 50%.

      #gallery-wrap {

  2. Murthy AVSN says:

    Great work dude its made me to do lot

    1. Jamy Golden says:

      Awesome :) thanks

  3. chris says:

    would it be really difficult to have it auto-scroll at a specified speed and than cycle back to the first image when it reaches the end?

    1. Jamy Golden says:

      Have a look at this

    2. Nick says:

      If you’re still looking for an easy way to loop back to the start of the Images mate here’s a way….

      Add a new var at the top that looks a bit like this:

      allImages = (totalWidth – imageWidth);

      And in the function:
      After the first IF statement add the IF statement

      f(jQuery(“#gallery”).position().left == stopPosition ){
      jQuery(“#gallery”).animate({left : “+=” + allImages + “px”});

      It’s not great but it’s what I was looking for..

      Hope this helps

    3. Stuart Kirkland says:

      This works a treat dude, how can i add a automatic animation on it??

    4. Manish C says:

      You can use the setInterval() and trigger() functions:

      setInterval(function() {
      }, 5000);

      The above example will simulate the clicking of the next button and advance the slideshow every 5 seconds.

  4. Justin says:

    Hey Jamy – love this – was exactly what I was looking for :)

    I have a question similar to Claus. I removed the width/height from the CSS for the images, and instead I am calling a script on load that resizes the images so that they fit within a specified width, and still maintain aspect ratio (since I have images of various sizes). This way they do not get smooshed.

    Now, the only problem that I am running into is that I can not seem to get the images to center vertically – I have tried so many different ways to do this but just coming up with anything that works.

    Wondering if you had any thoughts?


    1. Jamy Golden says:

      Hey Justin :)

      Try something like this:

      #gallery-wrap{display: table; margin: 0 auto;}

      That will horizontally centre a dynamic width. (I know you said vertically but I have a feeling you meant horizontally. If I’m mistaken just let me know)

    2. Justin says:

      Jamy, nope, I meant vertically :)

      What I ended up doing was to place a element before the image, and set the vertical-align to middle, and this centered the image as well.

      Not sure I completey understand, but was a suggestion I found elsewhere and worked great.

      Thanks again!


  5. Paladyn says:

    Hi Jamy
    Thanks for tutorial!
    Can you help me a bit with modifying your script a bit? :)
    I have a problem to make such gallery but with diffident image width. Height would be constant.
    So i need to calculate totalWidth from sum of images width (probably from image array in script), and move gallery by next (previous) image width.
    My biggest problem is to move gallery with right width.
    Any help will be appreciated. :)

  6. nick_ says:

    Hey, it seems that you got some errors on the HTML line at this point:

    <a href="#" rel="nofollow"><img src="images/prev.png" alt="" /></a>
    <a href="#" rel="nofollow"><img src="images/next.png" alt="" /></a>

    Can you upload a zip with the working example?
    Thx in advance.

  7. Xavi says:

    Hi there, really good tutorial!

    I don’t know if this is possible but imagine you want the reduce the width of your gallery so that the last picture appears just a bit.

    I tried to do it but the last picture doesn’t appear at all.

    Any ideia how can i overcome this issue?

    Cheers mate!

  8. Dyom says:

    where can i insert the jscript in wordpress?

    1. Jamy Golden says:

      Hi Dyom

      Just drop it in the header.php or footer.php. Remember to wrap it in the <script type="text/javascript"> tag.

  9. Aleksandar says:

    Thanks man! I needed some simple script that i can freely and easily customize… It worked great :)

  10. AbuBakar says:

    I am using this in one of my websites. It cool. Is it available as a download. I can see demo link at bottom of article but no download link. I am a lazy person and I would love to download it instead of copy pasting code and trying things :)

  11. rushabh says:

    hey how can i slide 4 images at a time with this code and next four images will come…???
    also same for prev button…

    1. Jamy Golden says:

      Change the javascript from: jQuery(“#gallery”).animate({left : “+=” + imageWidth + “px”}); to jQuery(“#gallery”).animate({left : “+=” + imageWidth * 4 + “px”});
      So basically you’d just be multiplying the amount it’s moving per click by 4. It would probably take a bit more code to make it only slide 1 imageWidth when you click next if there is only 1 image left to slide. I’m not sure if that makes sense, but I’m sure you’ll run into what I’m talking about once you do the change I mentioned.

  12. Karolina Nilsson says:


    Thanks for a great tutorial.

    I’m a bit lost in the whole jquery department.

    If I want the thumbs to show up in one pictureframe. How do I link them?

    And do I need to change the jquery in order to do this?

    Superthankful for any help you can give me.. :)

  13. Artful Dodger says:

    Great article! I know it’s old but if anyone’s wondering why there’s a little black dot between the images, it can be removed by replacing the #gallery li line with this:

    #gallery li{float: left; margin: 0 20px 5px 0; list-style:none;}
    1. JJ says:

      Artful Dodger,

      Actuallythie s missing from the CSS code:

      #gallery {list-style: none outside none;}

  14. KJ says:

    Hi guys,

    This looks really great, but is there any way the slider can keep on sliding after the last image, so that it shows img #1 again right after the last one?
    (Also in combination with sliding a full bar of images a time – 4 in this case.)

    That would make this one 100% happening, and very usefull with dynamic content generated from a database.

    Any help would be highly appreciated!

    1. Jamy Golden says:

      Hi KJ, I’m actually working on a plugin for this at the moment. I should be done in about a week or two. Let me know if you have any other specific requests and I’ll see if I can add it to the plugin.

    2. KJ says:

      Thanks for the quick reply Jamy!

      On the request level, it would be very usefull to run multiple galleries on one page as well. :-)

      Thanks again!

  15. John says:

    Thank you Jamy , Nice tutorial and Clear description

  16. Steveo says:

    Works fine but – I think I made a mistake – the slider knows the end for ‘Previous’ but not ‘Next’ just keeps going showing blank space..any idea what’s wrong please?

  17. Steveo says:

    If I’m guessing correctly, the jQuery needs to know the width of each ‘li’ to calculate the total width of the slider. I used your trick to allow me to use varying width images in my seems the downfall is that the jQuery can no longer calculate the total width and thus my ‘Next’ button shows infinite blank space. …. ?
    Any support appreciated.

  18. Steveo says:

    Looks like you dont moderate these comments any more so go ahead and delete all mine cuz I solved it (copied your CSS wrong), thanks buddy, nice job.

    1. Jamy Golden says:

      Hey Steve, All first time comments end up in a moderation pile and I didn’t get around to checking them today, so I definitely do still moderate them :p
      I’m glad you got your problem fixed up. If you have any future questions or comments, let me know!

  19. wow.. what a great tutorial… by the way is this working good in ie6?

    1. Thanks, and yes it is working in IE6+

  20. Paul says:

    Hey great tutorial, it really helped me out.
    Is is also possible to have the prev and next buttons hide when the gallery reaches the end or beginning?
    I have something working now for the starting position (with css); by default the prev. is hidden and when i click the next button the prev. is shown; so that works but I can’t seem to figure it out for the ending en start position.


    1. Hey, check out PlusShift. It’s a plugin I’ve created with this demo in mind.

      Attach the plugin and intialize the script like this:

      	disableLoop: true,
      	onInit: function( base ){
      	afterSlide: function( base ){
      		if ( base.slidePosition >= base.slidePositionMax ) {
      		if ( base.slidePosition <= 0 ) {

      If you have any questions, let me know.

  21. sarahjean says:

    Thank you Jamy– you just made my day a little easier. I know these slider tutorials are a dime a dozen, but this worked really well for showing me how to make it myself, and make it dynamic based on the content / container.

    1. Great! I’m really glad it helped :)

  22. Kyros Koh says:

    How to add a line of custom text that will be shown below with the image in the lightbox?

    1. Jamy Golden says:

      You could just add it after the <a> tag. Anything within the <li> tags would be part of the slide.

  23. Dmitriy Meshkov says:

    Thank you! I’ve used it and it’s perfect!

  24. jayendra says:

    Thanks to share this. Nice tutorial

  25. Akshat says:

    I want to use multiple sliders on a single page?
    Is that possible?

    1. Jamy Golden says:

      Hi, yes it’s possible. Try out PlusShift. It’s a plugin I’ve created based on this tutorial. Let me know if that helps.

    2. Hristo says:

      Could you please explain how? I am trying to rewrite that code for use with jQuery Mobile with finger gestures, so I couldn’t use PlusShift…

  26. princess says:

    really helps me a lot.. even though i spent a time to understand those codes.. thanks

  27. Stefan says:

    Thank you, was exactly what I was looking for.
    I’ve only one question, the Slideshow stops after some pictures.Is ist possible to start with the first image again when it reaches the end,like a carousel.

    1. Jamy Golden says:

      Hey Stefan, I’ve created a plugin, called PlusShift based off the Image Slider. I haven’t yet added functionality for it to ‘continue’ as if there isn’t an end, however it does go back to slide #1 at the end.

  28. sajid says:

    Great tutorial… Thanks for sharing.. i am going to use this is one of my own project

  29. amit says:

    Hey i tried adding your slider to my project.When i added about 6 images to “gallery” , the 6th image gets truncated and is displayed below.Could you helps me with this issue as i wanted to display the slider the way you have displayed in d demo.

    1. Jamy Golden says:

      Do you have a demo of the problem? Are all images the same width?

  30. six says:

    great one to learn for nubie like me! many thx

    but I’m wondering how to :
    – give “dot” indicators
    – last slide go to first slide (continous)
    – autoplay


    1. six says:

      no reply yet? please 😀

    2. Jamy Golden says:

      Hey, sorry I must have missed this. Have you had a look at PlusShift before? It may be what you’re looking for.

    3. six says:

      plusShift: yes and no.

      I need to understand how it works, so I don’t want to use this as plugin. So far, your tut is successfully works on my wp website, locally. But as i said, i need to know how do we use auto-play, continues slide, and indicators.


    4. six says:

      BTW, I just had a look again on plusShift, the indicator is not move (change) when I slide next/prev. Its only change when I clicked them.

  31. hooray says:

    can we know the current image url that selected?

    1. Jamy Golden says:

      What do you mean when you say “selected”? Do you mean as you click on an image? If you mean the current one when you click left/right, then which one seems like the current one to you? I ask because there are actually 2 images that could be ‘current’ at the same time.

  32. learning says:

    Thank you so much I am totally new to jquery and you’ve helped me to understand it a little more. Keep up the good work!

  33. Kay says:

    Thank you for this. However, I am having trouble with the lightbox / image pop-up feature of this. Is this bit of code in a previous article?

    1. Jamy Golden says:

      Hi Kay. Unfortunately I haven’t explained this in depth in a tutorial before, however there is some pretty helpful documentation for that on the fancybox site.

  34. Daniel says:

    …sorry for my english
    great tutorial and hello.
    maybe yo can help me.
    i have a base64 jpeg image in a var, how can i add this new image to the image slider when i press a button???
    I try in the onclick function add dynamically an li in the ul setting the src of the img with my new image, but after this i dont know how to refresh the image slider for show my new image.
    i have the same problem with almost all the jquery image slideshows plugins that builds-in from a specific ul in the onready, i dont find any use case to add the image dynamically.
    Can you help me??
    thank you very much.

    1. Jamy Golden says:

      Hi, yes this is possible :) I’ll create a little script for you to add-on to this jQuery image slider. I’ll reply and add it here in the next couple of days.

    2. Daniel says:

      thanks thanks thanks for your time. i’m waiting. thanks again

  35. Lu says:

    Hey dude – i love the mug shots and of course the neat jQuery code.

  36. Emil says:

    Hi there! Thanks for this tut, it works great! Just a quick question though, is it possible to have multiple rows displaying? I have hundreds of pics, and would like to get through them faster.

    1. Jamy Golden says:

      Yes it is possible. You would need to have a fixed slider width to achieve that, whereas currently this script is dynamically creating the width. That should help you head in the right direction. If you run into any problems let me know and I’ll see what I can do to help.

  37. Joy says:

    Good stuff dude!

  38. Sagar says:

    Nice tutorial. I havent tried it yet but will surely do so. I have one query I dont want to use the Anchor tag on images. So can I do it without them ? And You have used light box in your demo can you provide a tutorial for that too

    1. Jamy Golden says:

      Hey, yeah no problem, you can wrap the images in an anchor and there shouldn’t be a problem. As for the fancybox stuff: there is useful documentation on their site.

  39. snake says:

    I applied this slider with slight modifications (some margins changed, slider width, thumbnail size etc.). The slider generally works nice as I need but I am having a problem: when scrolling to the right there is a point before the last image when the slider restarts scrolling from the first image. After I changed the thumbnail size this effect happened the same but at another image number. Could you help for figuring out this problem?
    Thanks in advance

    1. Jamy Golden says:

      Hey, what script are you using to make the slider go to the first slide once it’s reached the end?

    2. snake says:

      that is exactly the problem, but not the goal: pressing the “next” button does not lead to reaching the last image. Just there is a point BEFORE the last image when scrolling starts from the first image. Generally I used the source from your article above, later I copied the script from your demo. When I tested the initial sample with few (4-5) images it works well. Now I have about 111 images into image folder.
      If this will help, I have online sample on my project (I can send its address by e-mail, since I don’t want to publish it).
      Thanks & regards

    3. snake says:

      Finally it works! Thanks for your great support! The problem was into jQuery library – after I upgraded it to the latest version all works perfectly! Once again – thanks for great help!

  40. Lythe says:

    Hi Jamy,

    I really like your image slider and I would like to use it on a website of mine.
    There is only one problem: I want to take images from a database with php/mysql – the connection with the database and showing the images goes well. But when I want to use the prev/next buttons it doesn’t work.

    I think it’s because he can’t make the calculation with the totalImages. Do you recognize this problem? Is it an easy fix?

    I’m a php starter, but it goes really well – but never did much javascript/jquery etc.

    Hope you can help me – can’t find another image slider alike! :)

    Thanks in advance,

    1. Jamy Golden says:

      Hi Lythe, the PHP/MYSQL shouldn’t have any direct affect on the javascript. This sounds like there is a problem with the slide’s width somehow. Do you have a link to an example problem?

    2. Lythe says:

      Hi Jamy,

      Here is the link to the page (no CSS yet – or whatsoever :) )

      It’s hard to set a width ’cause it changes with more images. Hope you can see where the problem is. Thanks in advance!

      p.s. great site btw, saw a lot of nice tutorials!

  41. Samz says:

    Very Nice… But i want to slide image auto.

    1. Jamy Golden says:

      Hey, have a look at PlusShift.

  42. z3phir says:

    nice tutorial one question how would this work for different width images ?

    1. z3phir says:

      i tried to build one but i have no ideea how to scroll forward or back

    2. Jamy Golden says:

      Hey, this tutorial doesn’t cater for images with a dynamic width. If you’d like you can have a look at a plugin called PlusShift. It can be used to recreate this example with images of different size.

  43. Mahmoud says:

    Thank you so much, really you make my day, so helpful, but i actually i had a problem here’s a screenshot for the problem :
    Any help i’ll appreciate it !
    Thanks again.

    1. Jamy Golden says:

      Hi, thanks for the kind words :) It seems slide elements don’t have a width. It’s tough to see exactly what the problem is since I don’t have a link to the page, but try and add display: block to the slide elements – It looks like they are <a> elements.

  44. Mahmoud says:

    Thanks for feeding me back as well, really appreciate it!
    Here’s a link for the page and here is a screenshot of what i need to fix , Sorry but the language is in Russian : )
    Thanks again.

    1. Jamy Golden says:

      It looks like it’s mostly working now. I’d definitely use PlusShift for something like this. It’s definitely a more solid solution.

  45. seema Morajkar says:


    I tried your code but it is showing simple html. All images showing like list menu.

    Is there need to add jquery library. I tried by adding
    but no use.

    Any other file need to attach.

    Please help me.

    Thanks for lovely tutorial and hoping for your valuable reply.


    1. Samuel says:

      Just add
      list-style-type: none;
      in the #gallery

    2. shobhit says:


      facing same problem like “seema Morajkar” pls help me out I am new in jquery to start learn more and more..

      I copied your code change in css but animation not takes place ….

    3. Jamy Golden says:

      It sounds like you haven’t added the CSS. Make sure the CSS is copied over and the CSS file is being loaded correctly.

  46. Mahmoud says:

    Jamy Golden
    Thanks a lot man really appreciate it that you help me out !

  47. pradeep kumar says:

    It is the best tutorial for image slider.

  48. I have added this plugin in my site but problem i am facing is last images last part always remain shows with next image like my image width is 992px when i click on next 970px hde but 22px stil there how to manage this..

  49. abid says:

    the demo is not working properly, i clicked on next button but there is no any action perform…

    1. Jamy Golden says:

      Which browser/browser version/OS are you using?

  50. Samuel says:


    Thanks for this great tutorial.

  51. JJ says:

    Hi Jamy,

    Thanks for great tutorial.
    How can I use this to display images of different widths. They are howerver the same height.
    I looked at PlusSlider but that only displays one image at a time and I ‘d like to display as many as can fit – just the way your tutorial here displays the images.


  52. nik says:

    Thanks a lot for tutorial, easy one!

  53. Priyam says:

    Hi Jamy,
    Firstly, thanx alott for ur tutorial which helped me to understand very easily some basic concepts of javascript.
    Now moving ahead it seems that when I copied your code the script did not work.
    I think there is some problem in :
    <a href=”#” rel=”nofollow”></a>
    <a href=”#” rel=”nofollow”></a>
    I think instead of “#” in the line there should be something else since “#” brings back to the same page.
    Please Help!!!!

    1. Jamy Golden says:

      In this case the <a> element could be any element. The href isn’t actually used at all. The # doesn’t actually bring you back to the same page, it merely jumps you to the top of the page, so the page doesn’t actually refresh. Do you have an online example of the problem?

  54. Hristo says:


    Thank you for a very clean and nice solution!

    I am looking for a way to use that in a mobile web app via jQuery Mobile. Could you clarify if and how can I use the script for multiple galleries in a single page?

    Thank you!

  55. jonny says:

    What if each image is a different size? will they all be scaled to the same size. If this is true then wouldn’t the proportions be off?

  56. lakshmikanth vallampati says:


    I would like to show an image slider in an imac dektop image… How to do this..?

  57. Danielle says:

    Hey Jamy,

    First of all this tutorial is great! I am new to Javascript and this is good to get my head around what the code is doing, to some extent (but thats probably just me).

    Im trying to adjust the code for my needs and it doesn’t seem to work. What I am trying to do is the same slide motion with the next and previous buttons, but only displaying one image at a time, rather than a row of 4 at a time. I assumed I just adjust the dimensions of the #gallery-wrap just to allow one image to be visible. But the #gallery doesn’t slide when my #gallery-prev and #gallery-next links are clicked. Does this mean I need to adjust the Javascript?

    I hope you can help or at least point me to a tutorial that might.


    1. JJ says:


      I would have a look at another jQuery plugin that Jamy wrote called Plus Shift: It is an upgrade from this tutorial as it can handle images with different widths.
      He also wrote another plugin called Plus Slider which has a whole slew of options.

  58. Thomas says:

    Thanks for this article! It really did help a newbie in jQuery as myself a lot… :)

  59. Gulzar says:

    I love it

  60. Danielle says:

    So, I was incredibly excited to find this as it’s exactly what I’ve been trying to do on my wordpress site. Unfortunately, I only know enough CSS to make me dangerous, and very little about java script. I added the html code and css, so far so good. Then I tried to copy the java script into the admin-js.php file of my wordpress theme (which apparently was the wrong thing to do!) and my whole website crashed. Oops. If I can figure out how to get it back, where should I put the java script portion? Do I just create a new file in the javascript folder? Any suggestions you have for a novice would be greatly appreciated!

    1. Jamy Golden says:

      Hi :) You would need to make sure jQuery has been included before you do anything. After the jQuery script in the physical html, you would then add the script:

      <script type="text/javascript">

      If you have any further problems/questions, feel free to contact me through my contact form.

  61. Such Ch says:

    I really like the simplicity of this tutorial. However, my gallery-wrap shows half of an image that has yet to come, as in, I want 3 images to show, but half the 4th image is showing as well, before I click next or anything. Overflow is set to hidden, I don’t think that is a problem, and the gallery length is calculated fine. Any thoughts? Sorry if this is a basic problem, I’m trying to get a grip on web design. Thanks!

  62. Singh says:

    Good article! Thanks a lot.

  63. Roger Blake says:

    If someone wants an infinite next and previous click through this plugin, like “when we reach the last then automatically the first will be shown”, then to do this we need to just include the following codes in the proper place.

    For Previous Link find the jQuery("#gallery-prev").click(function(){

    After the “if loop” add this code

    if(jQuery("#gallery").position().left == 0) {
      jQuery("#gallery > li:last").prependTo($("#gallery"));			

    And for the next button find jQuery("#gallery-next").click(function(){

    Within this function find the “if loop” and after that add this code

    if(jQuery("#gallery").position().left == stopPosition) {
      jQuery("#gallery > li:first").appendTo($("#gallery"));			

    Thats it. :)

    1. Raul S says:

      and animation? =|

  64. ravic says:

    thanks to explain jquery and its functionality very clear and understandable, but one question when i open the demo in a new tab it is showing all the images then after loading showing images in a div could you please tell why those are all displaying first time…
    once again thanks in advance.

  65. Jack says:

    When I click the Prev/Next navigation arrows, nothing happens, what could I be missing?

    1. Jamy Golden says:

      Could you send me an email and include a link to the problem? My email details are on the contact page.

  66. Emily says:

    Hi, just wondering if you are requesting any copyright or authorship statement when using your code?


    1. Jamy Golden says:

      Nope, you can use it for whatever you would like to use it for :)

    2. Emily says:

      Brilliant. Thanks for sharing:)

  67. joe savage says:

    Hi – I am new to jquery and I was wondering how can I make it for two rows instead of single?

  68. Deen says:

    Your code is very simple and understandable–is it possible that you know how to make a pagination for this slider?

    Thanks in advance.

    1. Jamy Golden says:

      Pagination for something like this doesn’t work as well as you’d think since there isn’t a clear position for a “current” slide. Is the current slide the most left slide? If so, how do you show the very last slide as the current slide? I could show a quick example of how you can create custom pagination on a normal slider such as plusslider – if you’d like.

  69. Hi!

    This looks like a great slider and something I’ve been looking for, but sadly I can’t get it to work…

    The debugger in Chrome says: “Uncaught ReferenceError: $ is not defined” at the top of the js-file. How do I do that?

    I’ve set up a very basic test site on

    Thanks for great community contribution!

    1. Jamy Golden says:

      The problem is that you’re not including the jQuery library before your javascript code.

  70. Nikhil Singh says:


    i want to create a content tab page/block, please check this at this page

    I would like to have guidance on how could I call content in this tabs when user would click on any tab, using jquery.

    Thank you!!

    1. Nikhil singh says:

      Thank you very much buddy :)

      have a good time :)

  71. Katherine says:

    I have nothing to show yet, but love the code! Thank you. I am being asked to position the Next and Prev arrows on the same line as the images.
    Here’s the current CSS:

    	margin: 0 auto; 
    	width: 732px;
    	float: left;
    	float: right;

    and HTML:


    Functionally, it works perfectly. But visually it needs a tweak. Thanks for any help!

  72. John says:

    There seems to be a problem when you zoom out the page with the sliding for the images (it seems not to slide correctly as with no zoom in-out).
    Is there any way you can fix it?

    1. Jamy Golden says:

      Yeah I see there is an odd bug. This is just a basic tutorial – If you would like to something like this in production, I suggest you look at a plugin like this:

  73. NewDev says:

    Ty your tutorial helped me a lot but i have a problem, I don’t think it’s because of the script but I ask anyway. The value of imageWidth is fine the first time I display my page (so display well all my pictures). But when I refresh my page, the value imageWidth change (is lesser than previously).

    Can you help me?

    Ty for your answer.

  74. Ertan SAYGI says:

    If anyone wants to move flexislider and carousel both together in a logical way, here is the script i wrote…Basically it calculates where carousel is and where image shown in flexislider is then animates to that position.

    	// Gallery
    		// Variables aren't use properly due to Webkit
    		var totalImages = $("#gallery > li").length, 
    			imageWidth = $("#gallery > li:first").outerWidth(true),
    			totalWidth = imageWidth * totalImages,
    			visibleImages = Math.round($("#gallery-wrap").width() / imageWidth),
    			visibleWidth = visibleImages * imageWidth,
    			stopPosition = (visibleWidth - totalWidth);
    			carouselCycle = 0;
    			flexiCycle = 0;
    			if($("#gallery").position().left  stopPosition && !$("#gallery").is(":animated")){
    				$("#gallery").animate({left : "-=" + visibleWidth  + "px"});
    			return false;
    		// Fancybox
    		$("#gallery li a").fancybox({
    			loop: false,
    			titleShow		: false,
    			margin      : [40, 0, 200, 0],
    			nextEffect	: 'none',
    			prevEffect	: 'none',
    			afterLoad: function(current, previous){
    				carouselCycle= Math.abs($("#gallery").position().left/visibleWidth);
    				flexiCycle = Math.floor(current.index/visibleImages)
    					if (previous) {
    						if (flexiCycle>carouselCycle)
    							$("#gallery").animate({left : "-=" + ((flexiCycle-carouselCycle) * visibleWidth) + "px"});
    						}else {
    							if (flexiCycle<carouselCycle) {
    								$("#gallery").animate({left : "+=" + ((carouselCycle-flexiCycle) * visibleWidth) + "px"});
    			helpers:  {
    				overlay : null
    1. Ertan SAYGI says:

      Sorry for this, if you can delete this one it’ll be better i guess :)

  75. Ertan SAYGI says:

    Great article Jamy…Thanks…

    If anyone wants to move flexislider and carousel both together in a logical way, here is the script i wrote…Basically it calculates where carousel is and where image shown in flexislider is then animates to that position.

    // Gallery
    // Variables aren’t use properly due to Webkit
    var totalImages = $(“#gallery > li”).length,
    imageWidth = $(“#gallery > li:first”).outerWidth(true),
    totalWidth = imageWidth * totalImages,
    visibleImages = Math.round($(“#gallery-wrap”).width() / imageWidth),
    visibleWidth = visibleImages * imageWidth,
    stopPosition = (visibleWidth – totalWidth);
    carouselCycle = 0;
    flexiCycle = 0;
    if($(“#gallery”).position().left stopPosition && !$(“#gallery”).is(“:animated”)){
    $(“#gallery”).animate({left : “-=” + visibleWidth + “px”});
    return false;
    // Fancybox
    $(“#gallery li a”).fancybox({
    loop: false,
    titleShow : false,
    margin : [40, 0, 200, 0],
    nextEffect : ‘none’,
    prevEffect : ‘none’,
    afterLoad: function(current, previous){
    carouselCycle= Math.abs($(“#gallery”).position().left/visibleWidth);
    flexiCycle = Math.floor(current.index/visibleImages)
    if (previous) {
    if (flexiCycle>carouselCycle)
    $(“#gallery”).animate({left : “-=” + ((flexiCycle-carouselCycle) * visibleWidth) + “px”});
    }else {
    if (flexiCycle<carouselCycle) {
    $("#gallery").animate({left : "+=" + ((carouselCycle-flexiCycle) * visibleWidth) + "px"});
    helpers: {
    overlay : null

  76. Chloe says:

    Hey, what pop out function did you use on this slide? (when you click on an image & it pops out the bigger version of the same image.)

  77. sol says:

    thanks a million for the slider easy and simple

  78. Raghavendra says:

    ultimate one… is it possible to improvise it and make it to auto sliding ??

    1. Jamy Golden says:

      Yeah, you could do something like this:

      var timer = window.setInterval(function(){
      }, 2000);

      Every 2 seconds the next button will be triggered.

    2. Negin Nickparsa says:

      wow cooOol ! how did you learn all this stuff? how many years you have implemented jquery stuff? I like to have these skills like you :)

    3. Jamy Golden says:

      I’m actually relatively new to all of this. I’ve been working with javascript for about 3 or so years.
      Just keep working on learning and try and answer other people’s questions on forums. It’s good practice!

    4. Mark van er Steen says:

      we do i place the timer script part?

  79. Krishan Kumar says:

    Jamy you have done very good work. I got much useful information from your blog.

  80. apurva says:

    hi!! I implemented this and it is working perfectly except for some design issues.I am getting a gap for on the left side of the gallery-wrap div. the image is not getting aligned exactly on top of the left arrow. Also I am getting some black dots between the imges(or the links div you can say).
    Please could you help me remove these problems? The rest is superb

    1. Jamy Golden says:

      Hi! Could you please create a jsfiddle of your problem?
      As for the black dots, I’m guessing li { list-style: none; } should fix that.

  81. avisek says:

    Hi Jamy,

    Can u explain, the stop position variable a bit more. I mean when u click on next it says that the gallery will slide -= image width. Why does it slide to the right when u click on next button and why to the left when u click on the prev button Need to understand the logic.

    1. Jamy Golden says:

      Imagine you see a window. And someone holds a long piece of wood behind the window. You can only see a piece of the wood, but you know there is more to the left and more to the right of the window which you can’t see. When you want to see some of the wood to the right (in other words, the next position), you will have to move the wood to the left. So to show the wood on the right you move it in a negative position. So that’s why the next button moves the list of images to the left. Does that make sense?

  82. Shyamli says:

    Hi..Thank you for this tutorial!!

    I have used this in one of my project but facing few issues.

    I have placed 3 image galleries on one page. Each gallery is visible when respective menu is selected from the select menu (which is working).

    Problem (1): The navigation buttons (both next and prev) is working for first slider only. But, for rest of the two galleries only next button is working and not prev.

    Problem (2): On first slider, if,for e.g, I am on 6th image and I select 2nd slider, then the slider starts from 6th image and not from the beginning.

    I know my issue is bit lengthy but I need this….Please help.


    1. Jamy Golden says:

      Are you having the same issues with the new script? (I’ve updated it).
      If you’re looking for a plugin that re-creates similar functionality to this tutorial I suggest looking at Moving Boxes.

    2. Shyamli says:

      Thanks for your reply..actually I resolved that issue.
      I will check out Moving Boxes for my future projects.


  83. James Cutler says:

    Great script,

    How do I make this scroll vertically rather than horizontally?

  84. Negin Nickparsa says:

    Thank you so much It is so nice! I really enjoined learning.I do not understand how left position and stop position ared how left position and stop 2 Aug<-> ah <>45atar.coeate-yoidth + “px”});
    return ss='avatager.lef 😕 >Rep> >Rev'>Reply

  85. 956
  86. 679 Pratck= M