Automatic Image Slider w/ CSS & jQuery
Blog » CSS/XHTML » Automatic Image Slider w/ CSS & jQueryAutomatic Image Slider w/ CSS & jQuery
With the release of the iPad and its lack of support for flash, it has stirred up a lot of debates regarding the future of flash. With this in mind, I believe it is wise to build simple widgets like the image slider using HTML/CSS/Javascript, and leave more interactive applications for flash if needed. The html based image slider will have its benefits with SEO and will also degrade gracefully for those w/out js.
The Wireframe – HTML
Start with having a wrapping container div called main_view, and two sections nested inside called image_reel and paging. The image_reel will contain the sliding images, and paging contains the paging controls. Take a look at the image below for a visual.

<div class="main_view">
<div class="window">
<div class="image_reel">
<a href="#"><img src="reel_1.jpg" alt="" /></a>
<a href="#"><img src="reel_2.jpg" alt="" /></a>
<a href="#"><img src="reel_3.jpg" alt="" /></a>
<a href="#"><img src="reel_4.jpg" alt="" /></a>
</div>
</div>
<div class="paging">
<a href="#" rel="1">1</a>
<a href="#" rel="2">2</a>
<a href="#" rel="3">3</a>
<a href="#" rel="4">4</a>
</div>
</div>
Styling – CSS
Take a look at the comments below for an explanation of the styles.
/*--Main Container--*/ .main_view { float: left; position: relative; } /*--Window/Masking Styles--*/ .window { height:286px; width: 790px; overflow: hidden; /*--Hides anything outside of the set width/height--*/ position: relative; } .image_reel { position: absolute; top: 0; left: 0; } .image_reel img {float: left;} /*--Paging Styles--*/ .paging { position: absolute; bottom: 40px; right: -7px; width: 178px; height:47px; z-index: 100; /*--Assures the paging stays on the top layer--*/ text-align: center; line-height: 40px; background: url(paging_bg2.png) no-repeat; display: none; /*--Hidden by default, will be later shown with jQuery--*/ } .paging a { padding: 5px; text-decoration: none; color: #fff; } .paging a.active { font-weight: bold; background: #920000; border: 1px solid #610000; -moz-border-radius: 3px; -khtml-border-radius: 3px; -webkit-border-radius: 3px; } .paging a:hover {font-weight: bold;}
Step 3. Setting up jQuery
For those who are not familiar with jQuery, do check out their site first and get an overview of how it works. I’ve shared a few tricks that I have picked up along the way, you can check those out as well.
Initial Step – Call the jQuery file
You can choose to download the file from the jQuery site, or you can use this one hosted on Google.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
Directly after the line where you called your jQuery, start a new <script> tag and start your code by using the $(document).ready event. This allows your jQuery code to run the instant the DOM is ready to be manipulated. The code you will be writing in the next few steps will all take place within.
$(document).ready(function() {
//Code goes here
});
Step 4. Bringing it to Life – jQuery
The following script contains comments explaining which jQuery actions are being performed.
Setting up the Image Slider
Start by showing the paging and activating the first link. Then we will calculate and adjust the width of the image_reel according to how many slides there are.
//Show the paging and activate its first link $(".paging").show(); $(".paging a:first").addClass("active"); //Get size of the image, how many images there are, then determin the size of the image reel. var imageWidth = $(".window").width(); var imageSum = $(".image_reel img").size(); var imageReelWidth = imageWidth * imageSum; //Adjust the image reel to its new size $(".image_reel").css({'width' : imageReelWidth});
Setting up the Slider Function and Timer
We first create the function for the slide event by itself (rotate). Then create another function (rotateSwitch) that will rotate and repeat that slide event (rotate).
//Paging and Slider Function rotate = function(){ var triggerID = $active.attr("rel") - 1; //Get number of times to slide var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide $(".paging a").removeClass('active'); //Remove all active class $active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function) //Slider Animation $(".image_reel").animate({ left: -image_reelPosition }, 500 ); }; //Rotation and Timing Event rotateSwitch = function(){ play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds $active = $('.paging a.active').next(); //Move to the next paging if ( $active.length === 0) { //If paging reaches the end... $active = $('.paging a:first'); //go back to first } rotate(); //Trigger the paging and slider function }, 7000); //Timer speed in milliseconds (7 seconds) }; rotateSwitch(); //Run function on launch
Take a look at this tutorial for an explanation of how the timer (setInterval) works.
Hover and Click Events
In case the user wants to view the slide for a longer period of time, we will allow the slider to stop when it is hovered. Another thing to consider is we should reset the timer each time the paging is clicked. This will prevent unexpected slide switches and allow for a smoother experience.
//On Hover $(".image_reel a").hover(function() { clearInterval(play); //Stop the rotation }, function() { rotateSwitch(); //Resume rotation timer }); //On Click $(".paging a").click(function() { $active = $(this); //Activate the clicked paging //Reset Timer clearInterval(play); //Stop the rotation rotate(); //Trigger rotation immediately rotateSwitch(); // Resume rotation timer return false; //Prevent browser jump to link anchor });
Inspiration
Below are some sites that use similar techniques, check them out for inspiration!
Related Articles
Similar Posts:
Tags: Intermediate, jQuery
This entry was posted on Monday, February 8th, 2010 at 12:03 am and is filed under CSS/XHTML. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.












Excellent, as usual.
Thanks.
Great tutorial thanks.
Awesome tutorial, Soh! I love the illustrations on the slides.
Glad you are finally back to posting tutorials Soh.
This looks excellent. Very nice effect and very useful. I’m a huge fan of your tutorials. They are always very detailed. See you tomorrow.
Nice to see you’re back with new tuts. Thanks.
Excellent! I liked how you kept it clean and simple! Keep up the good work!
Great stuff, even I understand how it works.
I’ll use that on my new website. Thanks a lot!
This is definitely something I have seen on a fair few websites.
Ill be keeping this in mind for the next project!
Thanks
fantastic one as usual. thanks dear
Ahmed
really a gr8 simple n understandable script.
thankx for sharing it.
lol i was just about to add one of these to a front page for a client when you came along with your solution.
the clients old website had flash on the frontpage for things like this and so i advised them to use alternatives.
great work as always
Very nice! Thank you.
Great Tutorial / Slider
Nice smooth automated effect
Great to see you back in action
Thank you for the tutorial
Building one of these is on my agenda for later in the week. Perfect timing. Thank you!
Finally
Great tut to start new season!
was looking for a simple way to do this…
i wanted an easy way to build a slider plugin for wp, and this worked perfectly…
thanks…
Thanks soh,
can you tell me, how i can put there a next and preview?
i look your code, and i dont know how you go that way..
i am a new in javascript, do you know where i can study that?
thx soh,
cya
Brilliant, is it possible to replace the images with div tags so that the jquery uses the div’s to swipe swipe rather than images?
Great tutorial thanks.
What will happen if the images are not of the same size?
Dope slide show – time to update the one on my site. Thanks for the tut!
Great tut, thanks!
Amazing as usual Soh! Thanks
awesome slider thanks
Gorgeous. Though, I’d suggest resetting the timer every time a user manually switches slides.
I’ve been looking for something like this for ages !
Thank You So Much !
Great tutorial Soh. This jQuery slider is awesome!
I’ve been searching everywhere for this jquery slider code! I even bought a month subscription on lynda.com for help. Couldn’t find it there either. Until now….THANKS TO YOU! THANK YOU. THANK YOU.
Fantastic as always, I love these things as they let users know how many images/banners are available to view and they are so easy to use.
Thanks again.
Amazing…
Superb this would be great to implement in a portfolio, Thanks.
There is a typo I think for tutorial9 link. The correct link is tutorial9.net, not .com
Soh thats a neat tutorial! Will use it in some of my projects.
Looking forward for next tutorial
excellent … very helpful as usual
Nice custom image slider with just few lines of code.
Intresting solution. Thanks
Amazing tut !
Hi Soh,
really intersting stuff, i was searching for a flash alternative for this…
I made a quick test here: http://www.jangeloen.be/new/test1.html to see what i could do with your idea. My question is now, is it in any way possible to have more than one of these running on one page? (is the only way by giving each instance its own piece of j code?)
What’s happening with the timer? It works fine for you on FF and IE?
Nice slider Soh
I disabled the timer (I just removed the “rotate” command in the timer section)
@Matias I will probably have to write an addon tutorial to this to show you~
@Duncan Turner yes, you can replace it with a div if you would like.
@John Johnson you should have them consistent in size since they are moving through the masked window which is a fixed size.
@Alique Azmi thanks for catching that! I fixed it to .net
@Jan Geloen I would advise not to have multiple automatic rotations running on the same page at once. But if you would like to use multiple image slider w/out auto rotations, I have another tutorial I will post later
Can somebody advice how to made fade effect when image is changes?
Thx Soh!
very useful
Awesome slider. So simple and easy to integrate, but still looks great.
Thanks for sharing.
Kevin
I’m looking forward to that tutorial ! thx a lot
Great tutorial! I love the outcome
Firstly, Soh, fantastic work with all your tutorials, I’ve found them to be invaluable. I was wondering what the best way to go combining this with a previous tutorial of yours would be (http://www.sohtanaka.com/web-design/css-on-hover-image-captions/)? Is their a simpler way than changing the class call to seperate ids (each with their own positioning)?
Thanks again for all your tutorials!
thats great stuff. thx a lot for this tutorial
This is great. Your jQuery tutorials are second to none. I love the design of your examples and I love how your code is clean and efficient.
I want to take this example and add a panning effect to the images.
Looks great thanks for making this.
One thing I’d like to point out however, it pauses when you hover over the image but not when you hover over the controls. This can be a little confusing until you realise what’s happening.
Should be easy to sort but I thought I’d mention it here.
This is a great find, thanks for posting it.
I am really new new to jquery and this to me quite a while to get working but finally did.
I have been trying to tweak it a bit more. I’d like to add a transparent bar and add a message scroller to it like they did on the site shown under inspiration ( http://www.netdreams.co.uk/
I tried all day trying to figure it out with no luck. I though the transparent image would be added like this but couldn’t get it.
.paging {
position: absolute;
bottom: 10px; right:;
width: 790px; height:37px;
z-index: 100;
/*–Assures the paging stays on the top layer–*/
text-align: right;
line-height: 40px;
background: url(image-files/transparent.png) no-repeat;
display: none; /*–Hidden by default, will be later shown with jQuery–*/
}
Sure there are a ton of people here that are smarter then me, would really appreciate any help and try to play it forward
thanks
Scott V aka fotodog13
muchas gracias, es fantastico, me será de gran utilidad…
saludos,
Felipe Saavedra E.
Nice tutorial.
Is there a way to enable the slidings only after all the images have fully loaded?
Great plugin, although I would suggest not changing the font-weight on hover. Changing the dimensions of any inline element on hover jerks the rest of the content around.
Nice work!
Nice! I use a similar jQuery solution for my webpage as well. But I like that this one pauses on mouse-over.
This is really nice the images are equally cute
just one thing though can the animation style be changed easily? I am pretty sure if I have this on my site I’ll get sued for causing epilepsy fits
Thanks for the excellent plugin. Perfect for a car website im working on right now! been after something like this for the past 30 minutes. Brilliant!
Hi, This is really nice slideshow, especially the pause on hover..
Just wondering, is there a way to put next and previous button on that slideshow.
Thanks.
Really simplistic and super cool too. I like it.
Perfect! This is exactly what I was looking for and the inspiration is great!
hi ……. how about using text over slideshow too…that will be great!
Hey, thanks for sharing this. I have been searching high and low for a slider that is easily customizable, and easy to understand and implement. Finally I can look no further. Waqas above has a great idea, any way to implement text padded to the left or right or top or bottom of the image as well? That would be even better .. not that I'm complaining mind you. I gave you a shout out on Twitter for this post ( http://clicky.me/GVB )… thanks again .
Nice tutorial! I’ve set an id to my different slides, and by adding #example
to the url it would go to that particular slide. However if I do this the menu will set the first tab to active in the navigation ofcourse and #example could be tab 3. Any Ideas on how to get around this ?
Thanks for sharing Soh!
It is very useful and it was easy enough to understand too. I’ll be looking for more of your posts! Thanks again!
Dude – awesome tutorial. I’ll let you know when my version is live on my website. We’re rolling out a new site design on Friday and we’ve been looking for an option of this sort. Yours seems to the easiest solution we’ve found.
Cheers,
JB
Fantastic Soh!
Your SEO is just pure awesome… I typed in “html, css, content slider” and your tutorial was in the top 5 results! Looks like you’ve come a long way with understanding JavaScript/jQuery. I’ve yet to really dig into it but maybe you could help me start that journey.
I was wondering if there is a way to repurpose this content slider to rely on a “Prev” and “Next” button. Basically, I already have a layout with the aforementioned type of pagination. How would I go about hooking this up with my pagination?
Thanks and nice work as always. Repping’ the South Bay!
useful tutorial
I like Dey’s idea of Next and Previous buttons.
I am also wondering why you didn’t us an ordered list for the paging? Are you able to?
The degradation when there’s no javascript is also very well done.
@Ben
It’s not much work to use an ordered list with this slider. As long as the tags have the rel attributes, you can wrap them in s and s.
I’m still trying to figure out how to implement a Prev-Next pagination. My JavaScript isn’t very strong as I’ve spent most of my resources learning PHP and MySQL. I do have a little bit of AS3 knowledge and so I can sort of understand JavaScript (both ECMA based languages) like the code that is already written, but to repurpose, that takes a bit of knowledge of syntax and I’m assuming DOM to target elements.
Soh what’s up Soh?
oops, my tags got stripped. The sentence should read, “you can wrap them in lis and uls.”
Really nice tutorial as usual!
I’m surfing your blog daily and things here keep amaze me
I read somewhere that you “love” wordpress, how would you go if you wanted to impement this slider on a wordpress site, and instead of showing images, it shows posts with a certain category? ie. “Featured posts”.
Regards
To2
one of the most elegant jquery carousels I’ve seen, and you also make it look so easy to implement, thank you for the great resource!
Great tutorial as always Soh!!! thanks a lot, just keep the great stuff coming
Hey! what do you know!
I got it working after a long night by adding “new WP_query” to generate a second (separate) loop
But I wouldn’t mind reading a tutorial here on your blog though!
-To2
What if we keep paging div empty and add this on top..
//get total items
var i = 1;
$(”.image_reel li”).each(function(){
$(”.paging”).append(’‘ + i++ +’‘);
});
P.S – I used instead of images in my reel
thanks, great tutorial…
@fotodog13 – Look at http://24ways.org/2009/working-with-rgba-colour for inspiration
Now can anybody tell me how to insert a loading animation whilst the first image is loading? Any tips would be useful thanks…
Rob.
Awesome Tutorial Soh!
Had a play around with the code last night and it worked really well.
Many thanks
Rob
@Rob_Jones
How about putting a lightweight ‘loading’ or ‘please wait’ background image into .main_view ?
A bit of a cheat but should do the trick.
Rob
Question: Is it possible to use an image map with this slider? My last slide (out of 18) has a link URL in the image.. my client would love to have that link active. I’m not sure if setting up an image map would make that area active on every slide, or just that last one.. Any insight is greatly appreciated!
I am not too good with JQuery…but I need something similar.
The images are loading on siteload..or are loading when the button is pressed?
simple but very nice and useful!