Create your own jQuery Image Slider
A few weeks ago I posted a tutorial called “Create an infinite polaroid image viewer with jQuery”. What is the difference between that tutorial and this one? I haven’t used the word “Slide” within the other article’s title because the images don’t slide, they fade. There is a slight CSS difference and quite a big jQuery/javascript difference between these two tutorials. We are now forced to use variables, otherwise the javascript becomes absolutely unmanageable.
I think it’s important to imagine what the HTML and CSS should be doing in order to create the component before we actually create the javascript. That way it’s easier to keep our eyes on the ball. Common things that cross my mind before developing the javascript 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.
The HTML
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 id="gallery-wrap">
<ul id="gallery">
<li><a href="image1.jpg"><img src="thumb1.jpg" alt="" /></a></li>
<li><a href="image2.jpg"><img src="thumb2.jpg" alt="" /></a></li>
</ul>
</div>
<div id="gallery-controls">
<a href="#" id="gallery-prev"><img src="images/prev.png" alt="" /></a<
<a href="#" id="gallery-next"><img src="images/next.png" alt="" /></a>
</div>
#gallery-wrap will be the visible area.
#gallery is the unordered list.
#gallery-controls contains the next and previous controls.
Generally an image slider would contain more than 2 images (such as the demo) but I’ve left out most of them for readability.
The CSS
#gallery-wrap{margin: 0 auto; overflow: hidden; width: 732px; position: relative;}
#gallery{position: relative; left: 0; top: 0;}
#gallery li{float: left; margin: 0 20px 15px 0;}
#gallery li a img{border: 4px solid #40331b; height: 175px; width: 160px;}
#gallery-controls{margin: 0 auto; width: 732px;}
#gallery-prev{float: left;}
#gallery-next{float: right;}
The most important thing here is to set #gallery to ‘position: relative’ and to set #gallery-wrap to ‘overflow: hidden’. Other than that, it’s quite standard CSS.
The jQuery/Javascript
This is where the magic happens.
$(document).ready(function(){
// Gallery
if(jQuery("#gallery").length){
// Declare variables
var totalImages = jQuery("#gallery > li").length,
imageWidth = jQuery("#gallery > li:first").outerWidth(true),
totalWidth = imageWidth * totalImages,
visibleImages = Math.round(jQuery("#gallery-wrap").width() / imageWidth),
visibleWidth = visibleImages * imageWidth,
stopPosition = (visibleWidth - totalWidth);
jQuery("#gallery").width(totalWidth);
jQuery("#gallery-prev").click(function(){
if(jQuery("#gallery").position().left < 0 && !jQuery("#gallery").is(":animated")){
jQuery("#gallery").animate({left : "+=" + imageWidth + "px"});
}
return false;
});
jQuery("#gallery-next").click(function(){
if(jQuery("#gallery").position().left > stopPosition && !jQuery("#gallery").is(":animated")){
jQuery("#gallery").animate({left : "-=" + imageWidth + "px"});
}
return false;
});
}
});
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 the variables:
totalImages = jQuery(“#gallery > li”).length
This returns a number equal to the amount of times the selector is returned as true. Basically, it tells us how many #gallery < li's exist.
imageWidth = jQuery(“#gallery > li:first”).outerWidth(true)
This returns the total image-width of the element. Total image-width meaning the width + margin + padding + border.
totalWidth = imageWidth * totalImages
This returns the total width of all the images.
visibleImages = Math.round(jQuery(“#gallery-wrap”).width() / imageWidth)
This divides the width of #gallery-wrap by the image-width. It is then rounded off to the nearest whole number.
visibleWidth = visibleImages * imageWidth
The visible width is calculated.
stopPosition = (visibleWidth – totalWidth)
The stop position is calculated by subtracting the visible width by the total width.
Summary of the the rest of the jQuery/javascript:
- When the DOM is ready
- If #gallery exists
- Declare variables.
- Set the #gallery to the width of all the images. This is done so that the ‘slide effect’ can function properly.
- When someone clicks on #gallery-prev
- If the ‘left’ CSS property is less than 0 and #gallery isn’t currently being animated
- Slide #gallery left equal to the total width of an image
- return false tells the link not to act like a normal anchor link
- When someone clicks on #gallery-next
- If the ‘left’ CSS property is greater than the STOP position and #gallery isn’t currently being animated
- Slide #gallery right equal to the total width of an image
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.
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?
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 {width:100%;
}
Great work dude its made me to do lot
Awesome
thanks
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?
Have a look at this
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?
Justin
Hey Justin
Try something like this:
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)
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!
Justin
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.
Hey, it seems that you got some errors on the HTML line at this point:
Can you upload a zip with the working example?
Thx in advance.
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!
where can i insert the jscript in wordpress?
Hi Dyom
Just drop it in the header.php or footer.php. Remember to wrap it in the
Thanks man! I needed some simple script that i can freely and easily customize… It worked great
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
hey how can i slide 4 images at a time with this code and next four images will come…???
also same for prev button…
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.
Hi!
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..
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:
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!
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.
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!
Thank you Jamy , Nice tutorial and Clear description
Works fine but – I think I made a mistake – the slider knows the end for ‘Previous’ but not ‘Next’ ..it just keeps going showing blank space..any idea what’s wrong please?
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 slider..it 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.
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.
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!
wow.. what a great tutorial… by the way is this working good in ie6?
Thanks, and yes it is working in IE6+
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.
Paul
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:
If you have any questions, let me know.
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.
Great! I’m really glad it helped
How to add a line of custom text that will be shown below with the image in the lightbox?
You could just add it after the <a> tag. Anything within the <li> tags would be part of the slide.
Thank you! I’ve used it and it’s perfect!
Thanks to share this. Nice tutorial
Hey,
I want to use multiple sliders on a single page?
Is that possible?
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.
really helps me a lot.. even though i spent a time to understand those codes.. thanks
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.
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.
Great tutorial… Thanks for sharing.. i am going to use this is one of my own project
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.
Do you have a demo of the problem? Are all images the same width?
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
thx
no reply yet? please
Hey, sorry I must have missed this. Have you had a look at PlusShift before? It may be what you’re looking for.
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.
thanks.
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.
can we know the current image url that selected?
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.
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!
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?
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.
…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.
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.
thanks thanks thanks for your time. i’m waiting. thanks again
Hey dude – i love the mug shots and of course the neat jQuery code.