Automatic Image Slider w/ CSS & jQuery

Blog » CSS/XHTML » Automatic Image Slider w/ CSS & jQuery

Automatic Image Slider w/ CSS & jQuery

PrintFebruary 8th, 2010

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.

Automatic Image Slider CSS jQuery

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.

Automatic Image Slider CSS jQuery

<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
});

Automatic Image Slider CSS jQuery

Inspiration

Below are some sites that use similar techniques, check them out for inspiration!

Automatic Image Slider CSS jQuery
Automatic Image Slider CSS jQuery
Automatic Image Slider CSS jQuery
Automatic Image Slider CSS jQuery
Automatic Image Slider CSS jQuery

Related Articles

Did You Enjoy This Post?

subscribeSubscribe via RSS ,by email, or by twitter to get all upcoming
tutorials and articles delivered straight to you.

Bookmark or Share this Post!

  • Digg
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Twitter
  • E-mail this story to a friend!

Tags: ,

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.

87 Responses to “Automatic Image Slider w/ CSS & jQuery”

  1. Huy Nguyen

    Excellent, as usual.

    Thanks.

  2. Hakan ERSU

    Great tutorial thanks.

  3. Martin

    Awesome tutorial, Soh! I love the illustrations on the slides.

  4. Design Informer

    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.

  5. Hung Bui

    Nice to see you’re back with new tuts. Thanks.

  6. Mikael Halén

    Excellent! I liked how you kept it clean and simple! Keep up the good work!

  7. Nicole

    Great stuff, even I understand how it works. :) I’ll use that on my new website. Thanks a lot!

  8. Krishna

    This is definitely something I have seen on a fair few websites.
    Ill be keeping this in mind for the next project!

    Thanks

    :)

  9. Ahmed Bolica

    fantastic one as usual. thanks dear
    Ahmed

  10. nikhil

    really a gr8 simple n understandable script.
    thankx for sharing it.

  11. thebettertwin

    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

  12. Caroline

    Very nice! Thank you.

  13. Dave

    Great Tutorial / Slider :)
    Nice smooth automated effect

  14. pffmihai

    Great to see you back in action :)

    Thank you for the tutorial :)

  15. Jim MacLeod

    Building one of these is on my agenda for later in the week. Perfect timing. Thank you!

  16. Max

    Finally :) Great tut to start new season!

  17. digibomb

    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…

  18. Matias

    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

  19. Duncan Turner

    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?

  20. John Johnson

    Great tutorial thanks.

    What will happen if the images are not of the same size?

  21. Abraham

    Dope slide show – time to update the one on my site. Thanks for the tut!

  22. S R K G

    Great tut, thanks!

  23. P-L Gendreau

    Amazing as usual Soh! Thanks :)

  24. free vectors

    awesome slider thanks

  25. Luke

    Gorgeous. Though, I’d suggest resetting the timer every time a user manually switches slides.

  26. Ciwan Kurd

    I’ve been looking for something like this for ages !

    Thank You So Much !

  27. Jonny

    Great tutorial Soh. This jQuery slider is awesome!

  28. L.A.Design Junkie

    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.

  29. Mark Garwell

    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.

  30. bee

    Amazing…

  31. Danilux

    Superb this would be great to implement in a portfolio, Thanks.

  32. Alique Azmi

    There is a typo I think for tutorial9 link. The correct link is tutorial9.net, not .com

  33. Kristjan

    Soh thats a neat tutorial! Will use it in some of my projects.

    Looking forward for next tutorial ;)

  34. zeejah

    excellent … very helpful as usual

  35. Rex S. Sacayan

    Nice custom image slider with just few lines of code.

  36. SM

    Intresting solution. Thanks

  37. Spartan

    Amazing tut !

  38. Jan Geloen

    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?)

  39. mat

    What’s happening with the timer? It works fine for you on FF and IE?
    Nice slider Soh

  40. Jan Geloen

    I disabled the timer (I just removed the “rotate” command in the timer section)

  41. Soh

    @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 :-)

  42. Pavel

    Can somebody advice how to made fade effect when image is changes?

  43. Rafael R.P (Raff)

    Thx Soh!

    very useful :)

  44. Kevin

    Awesome slider. So simple and easy to integrate, but still looks great.
    Thanks for sharing.

    Kevin

  45. Jan Geloen

    I’m looking forward to that tutorial ! thx a lot :)

  46. Marcell Purham

    Great tutorial! I love the outcome :)

  47. Robert Tilt

    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!

  48. Zrce Urlaub

    thats great stuff. thx a lot for this tutorial

  49. Josh

    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. :-)

  50. Ryan

    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.

  51. fotodog13

    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

  52. felipe saavedra

    muchas gracias, es fantastico, me será de gran utilidad…

    saludos,
    Felipe Saavedra E.

  53. abhijit

    Nice tutorial.

    Is there a way to enable the slidings only after all the images have fully loaded?

  54. Zach Leatherman

    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!

  55. Stereohero

    Nice! I use a similar jQuery solution for my webpage as well. But I like that this one pauses on mouse-over.

  56. Victoria

    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 :P

  57. web design staffordshire

    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!

  58. Neo

    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.

  59. Web Guru

    Really simplistic and super cool too. I like it.

  60. Andy

    Perfect! This is exactly what I was looking for and the inspiration is great!

  61. Waqas

    hi ……. how about using text over slideshow too…that will be great!

  62. Andrea

    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 .

  63. Yeggeps

    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 ?

  64. Ronnie Saini

    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!

  65. John Bates

    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

  66. Dey

    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! ;)

  67. tieutamtieu

    useful tutorial :)

  68. Ben

    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.

  69. Dey
  70. Dey

    oops, my tags got stripped. The sentence should read, “you can wrap them in lis and uls.”

  71. To2

    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

  72. Fabio

    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!

  73. greyk50

    Great tutorial as always Soh!!! thanks a lot, just keep the great stuff coming :P

  74. To2

    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

  75. Mohammed Ameenuddin Atif

    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++ +’‘);
    });

  76. Mohammed Ameenuddin Atif

    P.S – I used instead of images in my reel

  77. felipe saavedra

    thanks, great tutorial…

  78. Rob Jones (@Jones_Rob)

    @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.

  79. Rob

    Awesome Tutorial Soh!
    Had a play around with the code last night and it worked really well.

    Many thanks

    Rob

  80. 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

  81. Dey

    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!

  82. Real Estate Blog

    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?

  83. demir

    simple but very nice and useful!

  84. Casper

    Thanks!

    How to do fadeIn/fadeOut insted of slideing?

  85. aznoe

    dood you are an absolute legend!!! another great tutorial, thanks!

  86. Matt

    This was a great tutorial, easy to follow and worked great. However I am interested in figuring out how to apply thumbnail images rather than numbers like the “Tutorial9″ homepage slider.

    Any chance you could make an addition to this tutorial using thumbnail images that match the large image instead?

  87. Mauricio

    Very nice!!! It help me a lot. Thank you!

Speak Your Mind…

Need to post HTML code?
Use Postable for your convenience.

Don't have an Avatar?
Set up a Gravatar image now!

Blog Blog Categories

Popular Comments Popular Posts

Recent Comments Recent Comments