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.
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 class="gallery-wrap">
<div class="gallery clearfix">
<div class="gallery__item">
<img src="images/image1.jpg" class="gallery__img" alt="" />
</div>
<div class="gallery__item">
<img src="images/image2.jpg" class="gallery__img" alt="" />
</div>
</div>
<div class="gallery__controls clearfix">
<div href="#" class="gallery__controls-prev">
<img src="images/prev.png" alt="" />
</div>
<div href="#" class="gallery__controls-next">
<img src="images/next.png" alt="" />
</div>
</div>
</div>
.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.
The CSS
.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
$(window).load(function(){
// Fancybox specific
$(".gallery__link").fancybox({
'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`
$(".gallery__item").each(function(){
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
if($targetItem.length){
// 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
$targetItem.addClass("gallery__item--active");
// Remove the Active class from all other items
$targetItem.siblings().removeClass("gallery__item--active");
// Animate .gallery element to the correct left position.
$(".gallery").animate({
left : - newPosition
});
} else {
// Animate .gallery element to the correct left position.
$(".gallery").animate({
left : - maxScrollPosition
});
};
};
};
// Basic HTML manipulation
// ====================================================================
// Set the gallery width to the totalWidth. This allows all items to
// be on one line.
$(".gallery").width(totalWidth);
// Add active class to the first gallery item
$(".gallery__item:first").addClass("gallery__item--active");
// When the prev button is clicked
// ====================================================================
$(".gallery__controls-prev").click(function(){
// Set target item to the item before the active item
var $targetItem = $(".gallery__item--active").prev();
toGalleryItem($targetItem);
});
// When the next button is clicked
// ====================================================================
$(".gallery__controls-next").click(function(){
// Set target item to the item after the active item
var $targetItem = $(".gallery__item--active").next();
toGalleryItem($targetItem);
});
});
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:
$(".gallery__item").each()
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
if($targetItem.length){
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.
$(".gallery").animate()
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.
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
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:
jQuery(“#gallery-prev”).click(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
This works a treat dude, how can i add a automatic animation on it??
You can use the setInterval() and trigger() functions:
setInterval(function() {
$(“.gallery__controls-next”).trigger(“click”);
}, 5000);
The above example will simulate the clicking of the next button and advance the slideshow every 5 seconds.
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
<script type="text/javascript">
tag.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:
Artful Dodger,
Actuallythie s missing from the CSS code:
#gallery {list-style: none outside none;}
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.
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…
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.
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.
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.
Good stuff dude!
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
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.
Hi,
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
Hey, what script are you using to make the slider go to the first slide once it’s reached the end?
Hi,
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
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!
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,
Lythe
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?
Hi Jamy,
Here is the link to the page (no CSS yet – or whatsoever π ) http://vanbakelmuseum.nl/pages/schilderijentest.php
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!
Very Nice… But i want to slide image auto.
Hey, have a look at PlusShift.
nice tutorial one question how would this work for different width images ?
i tried to build one but i have no ideea how to scroll forward or back
http://jsfiddle.net/Zv24a/5/
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.
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 : http://owely.com/91dYzs0
Any help i’ll appreciate it !
Thanks again.
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.Thanks for feeding me back as well, really appreciate it!
Here’s a link for the page http://www.sst.by/Proftren.ru/item.php and here is a screenshot of what i need to fix http://owely.com/51jnQ3w , Sorry but the language is in Russian : )
Thanks again.
It looks like it’s mostly working now. I’d definitely use PlusShift for something like this. It’s definitely a more solid solution.
hi
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
http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js
but no use.
Any other file need to attach.
Please help me.
Thanks for lovely tutorial and hoping for your valuable reply.
Thanks
Seema
Just add
list-style-type: none;
in the #gallery
Hi,
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 ….
It sounds like you haven’t added the CSS. Make sure the CSS is copied over and the CSS file is being loaded correctly.
Jamy Golden
Thanks a lot man really appreciate it that you help me out !
It is the best tutorial for image slider.
thanx
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..
the demo is not working properly, i clicked on next button but there is no any action perform…
Which browser/browser version/OS are you using?
Hi,
Thanks for this great tutorial.
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.
Thx,
JJ
Thanks a lot for tutorial, easy one!
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!!!!
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?
Hello.
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!
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?
Hi,
I would like to show an image slider in an imac dektop image… How to do this..?
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.
Thanks!
Danielle,
I would have a look at another jQuery plugin that Jamy wrote called Plus Shift: https://github.com/JamyGolden/PlusShift It is an upgrade from this tutorial as it can handle images with different widths.
He also wrote another plugin called Plus Slider http://css-plus.com/2011/01/plusslider-1-0/ which has a whole slew of options.
Thanks for this article! It really did help a newbie in jQuery as myself a lot… π
I love it
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!
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:
If you have any further problems/questions, feel free to contact me through my contact form.
Hey,
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!
Good article! Thanks a lot.
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
And for the next button find
jQuery("#gallery-next").click(function(){
Within this function find the “if loop” and after that add this code
Thats it. π
and animation? =|
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.
When I click the Prev/Next navigation arrows, nothing happens, what could I be missing?
Could you send me an email and include a link to the problem? My email details are on the contact page.
Hi, just wondering if you are requesting any copyright or authorship statement when using your code?
Thanks,
Emily
Nope, you can use it for whatever you would like to use it for π
Brilliant. Thanks for sharing:)
Hi – I am new to jquery and I was wondering how can I make it for two rows instead of single?
Your code is very simple and understandable–is it possible that you know how to make a pagination for this slider?
Thanks in advance.
~D.
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.
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 http://myedhec.com/slider
Thanks for great community contribution!
/Niklas
The problem is that you’re not including the jQuery library before your javascript code. http://css-plus.com/2010/03/6-steps-to-take-if-your-jquery-is-not-working/
Hi,
i want to create a content tab page/block, please check this at this page http://events.jquery.org/2010/sf-bay-area/
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!!
Check this out: http://net.tutsplus.com/tutorials/html-css-techniques/how-to-create-a-slick-tabbed-content-area/
Thank you very much buddy π
have a good time π
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:
and HTML:
Functionally, it works perfectly. But visually it needs a tweak. Thanks for any help!
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?
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: https://github.com/CSS-Tricks/MovingBoxes
Hi!
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.
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.
Sorry for this, if you can delete this one it’ll be better i guess π
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.
$(window).load(function(){
// Gallery
if($(β#galleryβ).length){
// 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;
$(β#galleryβ).width(totalWidth);
$(β#gallery-prevβ).click(function(){
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
}
});
}
});
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.)
I used Fancybox.
thanks a million for the slider easy and simple
ultimate one… is it possible to improvise it and make it to auto sliding ??
Yeah, you could do something like this:
Every 2 seconds the next button will be triggered.
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 π
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!
we do i place the timer script part?
Jamy you have done very good work. I got much useful information from your blog.
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
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.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.
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?
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.
Shyamli
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.
Thanks for your reply..actually I resolved that issue.
I will check out Moving Boxes for my future projects.
Thanks,
Shyamli
Great script,
How do I make this scroll vertically rather than horizontally?
Thank you so much It is so nice! I really enjoined learning.I do not understand how left position and stop position are working? I alerted the stop position and it is was a negative integer.however I am still confused how it is working
I thought it would be nice if forexample when the cursor will be on the “next” it will continuously go like a film or story telling but I do not know how it is possible to change the animate part π
Hey Jamy, this is a great tut… this tutorial looks great for something i’m trying to do… i was wondering how can i make the image at the middle get bigger…. thanks..
Are you looking to learn how to do it or for something that will solve your problem? If it’s the latter the have a look at this great plugin: http://css-tricks.com/moving-boxes/
If it’s the former let me know and I’ll see where we could add some js to add the functionality.
Hi Jamy,
I am new for all this also I am slow Lerner. Really you have done great work. I tried this and It works!!!! Thanks a lot.
Great! I’m glad it helped π
hey Jamy! Great work…love it. I’m looking for a automatic image slider without controls(prev,next). Can you help me in this?
Thanks in advance.
Have a look at something like Moving Boxes. I’m sure there are js options to hide the arrows. Alternatively you could hide them with CSS.
When the page is loaded the slider gets a jerk before it settle downs in place is there a way to not let it happen?
Yeah that happens because the page loads up the images before the script kicks them into the correct position. To get around this you could add a class to the slider with jQuery. You could then hide the images via CSS and only show them when that class is added. If you have any problems implementing this just let me know and I’ll help.
thanx friend it sure help me a lot bcz im begener in JQ but can u please tell what this part
“jQuery(“#gallery”).position().left ”
actually return
and one more Q is what is the function of ‘.animet’ here.
Check out these jQuery documentation links:
http://api.jquery.com/position/
http://api.jquery.com/animate/
Hi Jamy!
This what I was looking for. Im very very new at this so im having trouble with the javascript codes. I Created my HTML, CSS and Javascript documents copying everything you posted. but After the Javascript code im stucked. I dont understand how to declare variables, so could you please help me out? Thanks
here is what im stucked “Summary of the the rest of the jQuery/javascript:” i dont understand what to do
I’ve updated the article. Let me know if you’ve still got questions.
Damn. That’s a lot of comments to read through.
Jamy, has anyone posted (that you can recall) a bug on the last frame? After reaching the very last frame of images, clicking the next arrow again causes the frame to shift slightly. See the below screencast.
http://cloud.chrisburton.me/RnkZ
One such great tutorial for creating slider I was searching for.
Hi Jamy,
Thank you for a nice tutorial. I’m try to find the solution to slide 8 images at a time with this code. I saw the solution that you gave in 2010,to slide 4 images at a time that said
“Change the javascript from: jQuery(β#galleryβ).animate({left : β+=β + imageWidth + βpxβ}); to jQuery(“#gallery”).animate({left : “+=” + imageWidth * 4 + “px”});”
I think it’s not work for the updated version. Could you please help me with this. Thank you.
Hi Pat, you could do that by changing this line:
var $targetItem = $(".gallery__item--active").next()
to:
var $targetItem = $(".gallery__item--active").next().next().next().next()
So instead of sliding to the next item, slide to the next next next next item π
You would do the same with the
.prev()
.Will it work for the divs and li as well?
Yeah it should work for all elements.
great plus good effort…
Hi,
I just found this tutorial which was exactly what I was looking for so thanks!
The only thing I’m trying to figure out is how to have multiple sliders on a page. Is there a way to edit the existing code to allow for that?
I know it’s been mentioned earlier in the comments section and I tried PlusShift but I prefer not having a plugin and actually being able to follow the script and know how it’s working. Any help would be appreciated. Thanks again!
Hi. Yes you would have to do the above for each targeted selector on a page. Have a look at this article for a detailed explanation on the .each() functionality.
In the script below, all I am adding/replacing to the script in the article is the each function
$('.gallery').each(function(){
and for each element that was targeted I replace the selector with$(this).find('.selector')
. This way it looks at each link/gallery/item within each .gallery on the page and applies the functionality to all as separate components.The entire script would be:
Let me know if you have any questions about that.
Hello, This is what I want, thank you.
I get 2 problems using it when I put more than one slider in one page.
1. when I click one of the slider to move left or right, the others move at the same time.
2.As the others move along with the one I click, all sliders will stop moving if one of the slider has reached its last picture even though there are more pictures to show in other sliders.
So How can I keep only the one I click move? and be able to show all the pictures.?
i try this code, but it doesn’t work. I really need you help. Thank you in advance.
Hi Jay, have a look at this comment: http://css-plus.com/2013/10/create-your-own-jquery-image-slider/#comment-83862
That should answer your question. Let me know if you have any other questions.
Exactly what i need thank youuu
how can we make a looping slider that changes images and stops at the last image
Add the following just before the close of the
$(document).ready(function(){
great tut.. Excellent..
Hi JamyL
I do not need the effect when I click on the image, it will be pop up.
How to disable this effect ?
Thanks
Find this JS:
And remove it. It enables the fancybox functionality.
What to do when we want to slide more than one image at a time
I can use it for a website?
Yes you can use it for anything you’d like π
For Auto scrolling use below:
Nevermind, I have solved it. I made mistake in the javascript link. Thanks for this great tutorial!
How to make jquery(source plugins) compatible with Html file ?
Hi Jamy,
Thanks for your tutorial. I am stuck though. How do I insert the JQuery? I’m using Dreamweaver CC if that matters.
Also, I really want to make a basic slideshow banner where the picture changes automatically without the push of a button. Can you show me how to do that?
Thanks,
Michelle
Hi, great work sir! i have a question? How to have slow the slides when its clicks ? because it is a bit faster when you click next. Thanks for the reply.
Thanks man, couldn’t get i working but after downloading I saw the issues, thanks a million!
Hii i want to move this slider automatically .is it
possible???
Can some one help me to understand:
1. Why $(window).load() should not be $(document).ready() ? I use usualy $(window).load() to do stuff while loading
2 Why if($targetItem.length) ? .length of what? floated elements have a length? i use .lenght to check how much elements are in an array usualy
3. Why var newPosition = $targetItem.position().left; ? is not the element .gallery that moves to -left?
I hope some one can help me to understand this stuff. I`m a beginner π
$(document).ready()
is an event that runs when the DOM (Document Object Model) is ready. Basically that’s when the raw HTML has completed rendering. At this point the images haven’t completed loading yet.$(window).load()
event fires after the page has completed loading, so the images have finished loading.if($targetItem.length)
$targetItem is a jQuery dom element. These are stored in arrays, so one can see how many items have been selected by checking the length.var newPosition = $targetItem.position().left;
It is the gallery that moves left, however it needs to move to a certain position, and that position is the left position of the slide you want to display.Hello, how do I style the images to stay responsive with my browser size? Thanks π
Hello, how do I scale the images to be responsive when changing the browser size? Thanks!
thanks… this code technique help me a lot on creating my own image slider…. thanks again