A Simple jQuery Slideshow

In the interest of following jQuery’s motto of “writing less and doing more,” let’s write a simple slideshow using jQuery, JavaScript and a bit of CSS.

Simple jquery slideshow.

Download the complete slideshow here
Read the FAQs

For starters, our main goal should be keeping the markup as clean as possible:


<div id="slideshow">
    <img src="img/img1.jpg" alt="" class="active" />
    <img src="img/img2.jpg" alt="" />
    <img src="img/img3.jpg" alt="" />
</div>

Now let’s use CSS to position the images on top of each other and bring the active image to the top level with z-index:


#slideshow {
    position:relative;
    height:350px;
}

#slideshow IMG {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
}

#slideshow IMG.active {
    z-index:10;
}

#slideshow IMG.last-active {
    z-index:9;
}

Due to absolute positioning, we need to define the height of the slideshow DIV. Also, notice that we defined three different z-indexes—we will manipulate these soon using jQuery.

For the slideshow animation we are going to switch between each photo at a set rate. So let’s start by writing a function that brings in a new photo on top of the last active image:


function slideSwitch() {
    var $active = $('#slideshow IMG.active');
    var $next = $active.next();    
    
    $next.addClass('active');
    
    $active.removeClass('active');
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

Here we set a JavaScript interval to call slideSwitch() every 5 seconds. Then slideSwitch() applies the CSS class ‘active’ to bring the next image to the top of the stack. Since we will select the images more than once within slideSwitch(), we define the variables $active and $next for selector performance.

Next we should incorporate a fade animation. For a gallery like this, fade in and fade out are identical, but let’s not forget to think about what we fade against:


function slideSwitch() {
    var $active = $('#slideshow IMG.active');
    var $next = $active.next();

    $active.addClass('last-active');
        
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

We start by applying the ‘last-active’ class we defined earlier. Since ‘.last-active’ falls after ‘.active’ in the stylesheet, the z-index of 9 takes priority, and the top image drops back a level. Next, we set the opacity of the new image to 0 so that we can fade it in using the animate() function. Finally, we attach a callback to remove the z-index classes from the previous image when animate() completes.

Although our slideshow is working well, we should make it more robust by building in some default variables. First, let’s define a default active image, in case we need to put less stress on the back-end. Also, we can use defaults to make the gallery animation loop.


function slideSwitch() {
    var $active = $('#slideshow IMG.active');

    if ( $active.length == 0 ) $active = $('#slideshow IMG:last');

    var $next =  $active.next().length ? $active.next()
        : $('#slideshow IMG:first');

    $active.addClass('last-active');
        
    $next.css({opacity: 0.0})
        .addClass('active')
        .animate({opacity: 1.0}, 1000, function() {
            $active.removeClass('active last-active');
        });
}

$(function() {
    setInterval( "slideSwitch()", 5000 );
});

We first define a default image for the $active variable, which interestingly enough needs to be the last image on the stack. This is because through absolute positioning, the last image appears on top, and we need to start with it if we want to avoid any flicker.

For the loop it is pretty simple: all we have to do is point the $next variable to the first image once it has gotten to the end of the line.

If you want to improve this function, try setting the animation speed with a variable so the main slideshow function can be thrown into the core and left alone. Also, this slideshow is easily converted to support DIV’s instead of IMG’s—try programming a slideshow with more content.

Now for a challenge: the gallery flickers when the images first load, but it can be fixed without touching the JS or markup at all. Bonus points to whoever figures it out and posts a comment.

Download the complete slideshow here
Read the FAQs



Jon Raasch

Jon Raasch is a UX nerd and free-lance web designer / developer who loves jQuery, Javascript & CSS.




You Might Also Like:


219 Comments to “A Simple jQuery Slideshow” RSS 2.0

  1. edu says:

    So far, (so simple) so good. Thanks for sharing this. It just work like a charm, so smoothly. I´ve been trying different jquery slideshows for days but they were too complex and bulky or hard to implement for non developpers like me and all I needed was this, a few images with a smooth fade transition.

    Nice blog. Keep it up!

  2. JeremyB says:

    Thank you for this! It works wonderfully with just images. However, I’d like each image to be a hyperlink, and when I wrap it in the appropriate tags, the fade does not work properly. Any advice?

  3. Jon Raasch says:

    Replace every “IMG” with “A” in the Javascript and CSS. If you are using the “active” class, attach it to the anchor (A) tag instead of the image.

    A more robust solution is to wrap each frame in a div and target the div’s instead of the images (or anchors). This would allow you to add text, multiple images, etc.

  4. JeremyB says:

    To answer my question, it was because the css and js files referenced switching images, not divs. Wrapping the hyperlinked images in divs and changing the references in the css and js files fixed it all. I’m a javascript n00b so sorry if this is totally obvious. Thanks again!

  5. JeremyB says:

    OK, new problem: A js-based dropdown menu disappears behind my slideshow. I’m thinking this is a z-index problem but nothing seems to work. See it in action at http://www.arenaracinggr.com

  6. JeremyB says:

    Annnd it was a z-index problem. Sorry to keep spamming up this board. Feel free to delete my comments, and thanks again for the excellent work.

  7. tudor says:

    to show 1st pic and avoid flickering I did:

    $(document).ready(function(){
    $(‘#slideshow IMG’).css({opacity: 0.0});
    $(‘#slideshow IMG:first’).css({opacity: 1.0});
    setInterval( “slideSwitch()”, 2000 );
    });

    and set the 1st picture to class=”active”. maybe it’s not the best way

  8. Looks something with those first and last PNGs does it? Are you preloading that? Hmm, this is a pretty good puzzle. Any hints?

  9. Jon Raasch says:

    OK here’s a hint: Tudor was on the right track with attacking the opacity value, since we target this attribute with our jQuery fade function. You could use his solution—it isn’t very resource intensive because it only loads once.

    However, these days it’s important to use as little JavaScript as possible. Try adjusting the CSS directly, instead of modifying it thru the DOM with jQuery.

    Thanks for reading and good luck!

  10. Start images with opacity:0.0; via CSS in the #slidehow block?

  11. Except for the IMG.active image, that is.

  12. Jon Raasch says:

    Great work Geoff, that’s the winner!

    By handling the opacity values with the stylesheet and not the JS, you make sure that you are both conserving resources and loading the images with these styles already attached. When coding a JavaScript heavy front end, I like to think of the stylesheets as sort of a base state, which I later manipulate thru scripting.

    If you’re a cut-and-paster here’s that portion of the CSS:

    
    #slideshow IMG {
        position:absolute;
        top:0;
        left:0;
        z-index:8;
        opacity:0.0;
    }
    
    #slideshow IMG.active {
        z-index:10;
        opacity:1.0;
    }
    
  13. Pietro says:

    Great script but have one issue — I’m using a DIV instead of IMG and everything plays fine but the first div seems to want to wait a couple second before loading. Once it loads all’s well and the script loops perfectly. Not sure what the resolution might be but would take any and all hints. THANKS!

  14. Yay! Makes total sense once you think about it (as most puzzles do). Thanks for the nifty script!

  15. Cool.. thanks for this blog mate.

  16. chris says:

    this is great, it works perfect!

    one problem is when you switch between tabs in FF, it changes images but without the fade.

    is that a problem or just me?

  17. Jon Raasch says:

    Hey Chris,

    This slideshow works in all major browsers so the problem must be on your side.

    One of my favorite parts about jQuery is that it has been thoroughly engineered to work in every browser you’d want. It takes a lot of the guesswork and hacking out of Javascript, so you shouldn’t worry about JS problems. Look instead to your stylesheets—I’d guess you have a z-index overwriting the one we set in the slideshow CSS.

    Good luck!

  18. chris says:

    Alright thanks for the quick reply.

    I am going to implement it in some websites now :D

    thanks again for this!!!

  19. Benek says:

    This is brilliant. Worked perfectly for me.

    As a front-end designer who’s just getting into jQuery I found using this a great learning experience, and it’s so much better and more lightweight that using a big slideshow plugin that’s way more than I need.

    Thanks for sharing!

  20. barney says:

    This is sweet, I just have one question? Do the images have to be the same size because if they are not they show up behind the active one. Can the images not be preloaded to avoid this?

  21. Helmut says:

    Hey!
    Thanks for your script. I added some lines to enhance the behaviour – I wanted the images to be centered and don’t overlap each other (occurs if some have smaller width than others)
    (My slideshow uses divisions – inside them are image-elements; the size of the slideshow is fixed)

    #slideshow {
    position: relative;
    width: 450px !important; /*set your width*/
    height: 299px !important; /*set your height*/
    margin-right: 20px;
    margin-left: 20px;
    background-color: #000000; /*i needed a black background*/
    }
    #slideshow div {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    opacity: 0.0;
    text-align: center;
    }
    #slideshow div.active {
    z-index: 102;
    opacity: 1.0;
    }
    #slideshow div.last-active {
    z-index: 101;
    }

    function slideSwitch() {
    var $active = $(‘#slideshow div.active’);
    if ( $active.length == 0 )
    $active = $(‘#slideshow div:last’);
    var $next = $active.next().length ? $active.next()
    : $(‘#slideshow div:first’);
    $active.addClass(‘last-active’)
    .animate({opacity : 0.0}, 1000);
    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }

    I added an animation to crossfade the last-active and active element.

    Thought I just comment this, if somebody wants crossfading images with a certain background.

  22. Helmut says:

    forgot something: the last-active class, their assignments and deletion can be deleted ;)

    and to avoid overlays in IE add
    “filter: alpha(opacity=0);” in #slideshow div and
    “filter: alpha(opacity=100);” in #slideshow div.active
    to your css

  23. Tim Parkes says:

    you are a lifesaver, i’ve been messing with complicated slideshows for ages trying to get them to work, this is perfect and only took half an hour to implement!

    thank you!

  24. William B says:

    Thanks to Jon and Helmut… This is great. I was playing around with this and tried putting the slideshow div inside of a table. After that the fade effect stopped working in IE even though it still works in FF. The pics still rotate just no fade in fade out. Any ideas on how to make it work nested inside a table in IE?

  25. Nick says:

    Hi,

    Thanks for this slideshow, its almost what was I’ve been looking for.

    However, I’m after a way of pausing the slideshow when you over the mouse over.

    Adding one line in this –

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    $(‘a’).hover(‘pause’); //extra line here is here!
    });
    }

    Causes the images to pause, but the links still cycle through as normal.

    My jquery/javascript knowledge is limited, so wondering if you know of a solution to this?

    :)

  26. Jon Raasch says:

    Hi Nick,

    First when you set the interval, you want to assign it a variable:

    
    var playSlideshow =  setInterval( "slideSwitch()", 5000 );
    

    Next use the jQuery hover method:

    
    $(’#slideshow').hover(function() {
        clearInterval(playSlideshow);
    },
    function() {
        playSlideshow =  setInterval( "slideSwitch()", 5000 );
    });
    

    The jQuery hover method can be used to assign two functions: one for mouseover and one for mouseout. Here, on mouseover we clear the interval that is playing the slideshow and on mouseout we reset the interval to play the slideshow again. This should work to pause the slideshow when you hover your mouse over it.

    Hope this works out for you, good luck!

  27. Nick says:

    Hi Jon,

    Thanks! Works fine in FF3, IE6 & 7, Opera and Safari on windoze. However, I noticed a problem in FF3 on the mac, where you have to click away from the window or elsewhere on the page (or refresh) to make the slideshow re-slide again, otherwise it stops on that particular slide. I presume it does the same on Safari on the mac.

    Although its a minor niggle and probably not much to lose sleep over (given the amount of mac users compared to windoze) but its still worth investigating for 100% usability across all platforms and browsers.

    :)

  28. Rick says:

    This is just great :) Nice work. I think what would make it about perfect would be to have it pull the images from a directory. Possible? …My skills are limited, but I’ll give it a try…

  29. Dave Griffin says:

    Hi,

    Just wanted to say this is an awesome slideshow solution, super simple but exactly what I have been looking for. As the other dudes have been saying in the comments lots of ‘other’ plugins are just too complex for my simple little brain.

    This will now be used on my new photography portfolio website.

    Thank you very much.

    Dave

  30. Nick says:

    Rick – You can use php to grab all the images from a particular folder and put that in the div where the slideshow goes.

    A basic php script that pulls in the files from a particular folder for you to start off with -

    <?php
    $dir = “images/”;
    $dh = opendir($dir);
    while (($file = readdir($dh)) !== false) {
    echo “”;
    }
    closedir($dh);
    ?>

  31. Jon Raasch says:

    Hi Rick and Nick,

    A script to pull the images from a directory sounds like a great idea, but let’s not involve PHP at this level. (Right now the slideshow works in basic HTML or any backend language). Instead look to jQuery’s very easy to use ajax() method. This could be used to hit Nick’s PHP page..but let’s also build in some recursion, in case the directory contains subdirectories.

    Good luck and if anyone gets this going, please post!

  32. You’ve got some link love.. Great job on making a lightweight and easy to use slideshow:

    9 Jquery Slideshow Applications You CANNOT Miss

  33. I keep getting “$active.next is not a function”. If I do an alert($active) it returns false. For some strange reason, the selector on line 2 doesn’t seem to work (works outside the function though).

    Any ideas?

  34. pavlentij says:

    Great idea!
    Thanks!

  35. Jon Raasch says:

    Hey Adrian,

    If I had to guess, I’d say you are either not loading jQuery or not defining the $active variable. Also try console.log() in Firebug instead of alert(), it will give you more meaningful results.

    Good luck!
    -jr

  36. Bart says:

    Thx for the great article. Easy to implement!

  37. Saurabh says:

    Wow ! simple and esay way to do the slideshow…
    Thanks for this slideshow, its almost what was I’ve been looking for.

  38. Cory says:

    I’m trying to use your script above but instead of on img’s i’m using it on divs. It works great in FF but unfortunately in IE7 it produces an error. Here’s my code:

    a link to the example i’m trying to use is:
    http://dad.corydorning.net

    any help is greatly appreciated!

  39. Julian says:

    Is it possible to have a different duration for each slide? E.g. slide #1 appears for 2 seconds, slide #2 appears for 4 seconds?

  40. r-doll says:

    Thanks for this, its great. :)

    Like Helmut, I had varying sized images, so also set width/height on #slideshow also added overflow:hidden; to ‘trim’ down images to fit.

  41. eric says:

    Thanks for your efforts, Helmut. This worked great and was by far the easiest jquery slideshow that I found to implement.

  42. Tom says:

    Excellent simple solution, ive got one problem and cant seem to find where the problem is, in FF3 – Chrome – Safari it works perfect, images and fades in correct order, I have tried it on IE7 and it works ok, but starts on the last image and misses the first image out in my sequence? any ideas?

  43. Tom says:

    dont worry forget that last post, ive found the problem, I had forgot to close off the div tag… it works perfect. excellent

  44. Tolis says:

    Thanks for the wonderful tutorial. I wonder if it is possible to go to a specific slide when you click a thumbnail.

  45. Alex Sharp says:

    Thanks for the great post and solid explanation of what’s happening throughout the code. I created a simple rails plugin that utilizes this code. “Here’s the link”:http://github.com/ajsharp/jquery_rails_slideshow/tree/master. Thanks again!

  46. Thank you for such a simple and easy to use solution for simple fade transitions!

  47. Barry says:

    Great script Jon, easy and also wanted the functionality on anchors, works like a charm.

    Any chance of randomizing the order in which the images/links appear?

    Cheers and thnx again for making life simpler

  48. Jon Raasch says:

    Hi Barry,

    To randomize which slide shows up, set the $next variable using this code instead:

    var $sibs  = $active.siblings();
    var rndNum = Math.floor(Math.random() * $sibs.length );
    var $next  = $( $sibs[ rndNum ] );

    Good Luck!
    -jr

  49. Barry says:

    Thnx Joh, it did the trick!

  50. Tina says:

    Hey Jon
    Any chance you could give us an example of how to pull images from a directory without php (or any other server-side language)? Thanks.

  51. PaoloTCS says:

    Any way to have the images come from a database? In Sql Server 2005, getting a random sequence of columns is easy. How would one then make them be used by this jquery app?

  52. SteveL says:

    Hey Jon,
    Great Script…When my page loads up with the slideshow, it’s kinda choppy. It shows each image loading, and when it finishes loading it’s smooth… I noticed that on this page it doesn’t do that. Do you have any ideas how to fix that? Thanks!

  53. SteveL says:

    PaoloTCS:

    What I would do is loop your images inside the DIV tag.
    So retrieve the image names from the database, and then put inside the div tag.

  54. Thanks for example. I just used it for a project I’m working on, and had no problems whatsoever, thanks again.

  55. kidprogramer says:

    help me !
    How I can use link in image and stop slide show when i move mouse on image.
    Thanks help!

  56. Hi!

    Since my customer wanted a site with two slideshows going on I had to modify this a bit… here you go:


    /* Modified version of http://jonraasch.com/blog/a-simple-jquery-slideshow to show slideshow in two separate places */
    function slideSwitch(switchSpeed,activeClass) {

    var $active = $('#slideshow IMG.' + activeClass);

    var $startPosition = ( activeClass == 'active1' ) ? $('#slideshow IMG:first')
    : $('#slideshow IMG:nth-child(2)');

    if ( $active.length == 0 ) $active = $startPosition;

    var $next = $active.next('IMG').next('IMG').length ? $active.next('IMG').next('IMG')
    : $startPosition

    $active.addClass('last-active');

    $next.css({opacity: 0.0})
    .addClass(activeClass)
    .animate({opacity: 1.0}, switchSpeed, function() {
    $active.removeClass(activeClass + ' last-active');
    });
    }

    $(function() {
    /* setInterval ( "slideSwitch(FADE_DURATION,'CSS-CLASS')", DELAY ); */
    setInterval ( "slideSwitch(1000,'active2')", 3000 );
    setInterval ( "slideSwitch(1000,'active1')", 3000 );
    });

    There’s one ugly thing however the “next(IMG).next(IMG)”-thing… is there some parameter or other easy way in which I could achieve the same effect? And this way is no good if I really easily want to change the number of slideshows going on.

    OK… and here comes the CSS:


    #slideshow {
    position: absolute;
    top: 190px; /* image top */
    left: 50px; /* left image, left edge */
    width: 100%;
    }
    #slideshow img {
    position:absolute;
    top: 0;
    left: 720px; /* right image, left edge */
    z-index: 8;
    }
    #slideshow img.active1,
    #slideshow img:first-child {
    left: 0;
    }
    #slideshow img.active1,
    #slideshow img.active2 {
    z-index: 10;
    }
    #slideshow img.last-active {
    z-index: 9;
    }

    Enjoy!

    cheers, Simon

  57. ron says:

    Do I actually put the java script on the html page or a seperate
    myjava.js?
    thanks,

  58. Doesn’t matter… but a separate file is probably usually preferable. Just look at how it’s done on this page. :)

  59. Dave says:

    Hi, great script but an IE user has just pointed out a javascript error in mine on line 19, saying that there’s something wrong with this:

    function slideSwitch() {
    – 2 var $active = $(‘#slideshow IMG.active’);
    3
    – 4 if ( $active.length == 0 ) $active = $(‘#slideshow IMG:last’);
    5
    – 6 var $next = $active.next().length ? $active.next()
    – 7 : $(‘#slideshow IMG:first’);
    8
    – 9 $active.addClass(‘last-active’);
    10
    – 11 $next.css({opacity: 0.0})
    – 12 .addClass(‘active’)
    – 13 .animate({opacity: 1.0}, 2000, function() {
    – 14 $active.removeClass(‘active last-active’);
    15 });
    16 }
    17
    18 $(function() {
    19 setInterval( “slideSwitch()”, 7000 );
    20 });
    21

    It still works perfectly, but the client is a bit pedantic and doesn’t like to see little yellow triangles in IE7. Any ideas (other than getting him to switch to FF)?

  60. Jon Raasch says:

    Hi Dave,

    This slideshow script works perfectly in all major browsers. Either it was copied incorrectly or there is a problem elsewhere in your code.

    Also just as an FYI, the line numbers in IE errors don’t typically align with an included Javascript…Typically I count the lines in the source code, including each src’ed javascript in that line number total.

    Thanks for reading and good luck,
    -jr

  61. Dave says:

    Thanks Jon, I’m no Javascript pro but I’ll keep trying to figure it out.

  62. Andrei Gonzales says:

    Excellent tutorial. Although I thought stating the opacity in the CSS doesn’t validate?

  63. Jon Raasch says:

    Hi Andrei,

    Honestly, I didn’t know that opacity broke CSS validation because I don’t really concern myself with validating my CSS. HTML validation makes sense to me because it makes cross-browser testing easier and ensures your code will be supported in future browsers. However with CSS I think it’s only important to use actual CSS tags that are supported by all major browsers.

    If you wanted, you could apply the opacity value to the pictures within the jQuery onload function, but this wouldn’t really solve the validation problem. When I, for instance, validate my HTML, I like to validate the GENERATED source (after the JS layer has been applied). If you only validate the on-page source your validation is incomplete.

    Now if you do the same for CSS, by conventional logic we shouldn’t be using opacity at all, since whether you apply it with JS or from the stylesheets, it’s invalid. And if we can’t use opacity at all, it makes all fade effects on the internet impossible (unless they’re in Flash). Additionally, since the jQuery library uses opacity, you couldn’t even use jQuery.

    Therefore I wouldn’t worry too much about validating the CSS for the simple jquery slideshow. No reason to stay true to a lofty goal of CSS validation if it prevents you from making the best site you can, when there’s a 99% chance your client doesn’t care one bit about validation.

  64. ron says:

    Great tut.
    one question I have my pics will not stack on top of each other but the jquery is working fine?
    What am I doing wrong in the css?
    Any suggestions are welcome.
    thanks much.
    RON

  65. Sougata says:

    Hi Helmut,

    could you show how you have implemented that separate slide show in live, please? cause I am trying to implement the same but .. couldn’t yet :-)

    Das

  66. Jon Raasch says:

    Hi Ron,

    Make sure the images have position: absolute; and that the slideshow wrapper has position: relative or some other position. If that doesn’t work, attach !important to those.

    Good Luck!
    -jr

  67. ron says:

    Got it figured out now.
    Thanks so much and it looks really nice.

    thanks again.

  68. LD says:

    Its really fantastic and quite easy to implement. it works superb after a littl bit changes.

  69. Sergio Pinto says:

    Hi Jon.

    I’m trying to randomize the slide show but without success, I’ve noticed you’ve already replied to a similar question, but I’m new to jquery and everything javascript for that matter, I’ve tried this out:

    function slideSwitch() {

    if ( $active.length == 0 ) $active = $(‘#slideshow IMG:last’);

    var $sibs = $active.siblings();
    var rndNum = Math.floor(Math.random() * $sibs.length );
    var $next = $( $sibs[ rndNum ] );
    var $active = $(‘#slideshow IMG.active’);

    $active.addClass(‘last-active’);

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }

    $(function() {
    setInterval( “slideSwitch()”, 5000 );
    });

    I’m sure it’s something ridiculous but could you give me a hand please.

    Thanks

    Sergio

  70. Sergio Pinto says:

    Hi Jon!

    Please ingonre my last comment, jquery is really great and easy once u get the hang of it, anyway I got it working :)

    Thanks for the tutorial.

    Cheers!

  71. ernesie says:

    Can someone please put all the working code together with all the fixes so that we can download.

  72. Chandler says:

    What would be the best way to traverse accomplish the same thing with the images being wrapped in anchor tags?



    I cannot seem to traverse the DOM correctly to accomplish this.

  73. Jon Raasch says:

    By popular request:

    Download the slideshow example files here

    Happy Coding!
    -jr

  74. Ronan Berder says:

    Hi Jon,

    I used you solution on a couple sites, mainly for promotional slideshows. However, in the the late version I felt like simplifying a bit your implementation: you can easily manipulate the DOM elements with the append function inspite of trying to emulate it with CSS:

    $(document).ready( function() {
    // Every six seconds execute the switchSlide() function
    setInterval( “switchSlide()”, 6000);
    });

    // This function takes the first .slide element and put at the end
    function switchSlide() {
    var slide = $(‘.slideshow .slide:first’);
    slide.hide();
    $(‘.slideshow’).append(slide);
    slide.fadeIn(‘slow’);
    }

    You can have a look at the result there: http://teddy.fr/blog/easy-and-maintainable-slideshows#slideshow

  75. Keith says:

    Jon,

    This is perfect and elegant!

    I’m trying to link a series of buttons to particular slides; how would I fire a specific slide when a button is pressed (i.e. how can I refer to a 3rd slide, say, rather than simply the next slide?)

  76. John P says:

    Jon,

    So simple and so instructive! Using z-index means that the image with class “active” is displayed alone when JavaScript is disabled. I real bonus!

    Many thanks.

  77. Robin says:

    Echoing SteveL of 12/9/08, any way to stall the script ’til all images are loaded? Thought $(function() might handle it, and I notice that’s in the display interval aspect, but not elsewhere. Ideas welcome, assuming I’m on the right track.

    Note, website noted is definitely a work in progress . . .

    Robin

  78. Rik Weber says:

    I love working through jquery examples – this works a treat!

  79. Jon Raasch says:

    Hi Robin, the slideshow doesn’t start until all the images are loaded, although the images will be visible on the page before the script starts (as John P mentioned above this is ideal in case Javascript is disabled)

    Good luck,
    jr

  80. robert says:

    thanks for the code dude! quick question: why does my first image spend so much longer on the screen than the other images? http://www.frontstreet.net/prototype/index.php Thanks!

  81. Jon Raasch says:

    Hi Robert,

    Good question! The first image stays up there longer because the slideshow script waits until all the images are loaded before starting.

    Thanks for reading,
    jr

  82. Nathan says:

    Hey

    Thanks for this, this is a great example of what is posisble and works really well!

  83. Tee says:

    I’ve tried adding background: url(../images/frame.png) no-repeat 0 0; to #slideshow IMG with no result.

    Can anyone tell me how to put a background image around the slideshow?

  84. Terry says:

    Jon,

    Great application of jQuery. I had it up and running in no time. I’d much rather use this than a Flash based slide show.
    I have one question though, is there a way to stop the slide show after the last image in the stack? a kinda loop=”off” mode.

    I’ve been looking at the code and can’t see an obvious solution.

    Terry

  85. chris says:

    Hey really like the slideshow thanks,

    i’m real new to Jquery and i just need the slideshow to play once i’m guessing there will be some loop function but as i said i am just starting out with jquery can anyone lend a hand cheers ?

  86. svenga says:

    nice slideshow cheers

  87. alberto lopez says:

    Nice Job!!

  88. Piotr says:

    Well done, thanks for sharing the script.

  89. Ronan Berder says:

    I put a bit more effort in my previous interpretation of your script and came up with something that handles a dynamic pager as well. You can find an example there: http://wiredcraft.com/node/4.

    I can have it cleaned and working with regular HTML output if anybody is interested, as it is designed for use with Drupal at the moment.

  90. rufus says:

    AWSOME! your website and this little plug-in.

    THANKS

    all the best.

  91. This is so cool. I have been using flash for things like this in the past. I feel like buying a good JQuery book now. Thanks for the tutorial.

  92. Kasun says:

    Amazing, Its so cool and easy to use. Thanks a lot.

  93. rufus says:

    AWSOMEEEEEEEE!

  94. robfield says:

    All: anyway to remove needing to set the image dimensions is multiple css divs ids? Would like to just set a single image dimensions in one place and have containing divs expand or contract to enclose new size of image. Having the tight coupling of multiple h & w settings seems like too much work?

  95. Jon Raasch says:

    Hey Robfield,

    There’s no need to set the image dimensions through the individual ids, just use CSS to set them all (as is done in the example).

    Good luck,
    jr

  96. robfield says:

    Jon, but does that still require we set the dimensions in more than one place, which is still a bit tightly coupled? Or are you suggesting I could set the dimensions of both divs via a variable in jquery so there would only be one dimension number to write, thus setting the css in multiple places via the variable? I’m trying to eliminate the write an actual number in more than one place, eg., h=100px, w=200px should only need to written once, otherwise it would be subject to human error?

  97. robfield says:

    Jon, FYI – forgot to tell you I’m reference your example 2, which has css showing the need for setting dimenstion in 3 separate divs.. having to keep all three dimension in sync could be a challenge. see below where height is set in 3 different divs:

    #slideshow {
    position:relative;
    height:400px;
    }

    #slideshow DIV {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    opacity:0.0;
    height: 400px;
    background-color: #FFF;
    }

    #slideshow DIV IMG {
    height: 150px;
    display: block;
    border: 0;
    margin-bottom: 10px;
    }

  98. Jon Raasch says:

    Hi Robfield,

    As mentioned in the tutorial you need to set the dimensions for both the slideshow wrapper, along with the wrapper of whatever it is you are rotating, due to absolute positioning. For instance, in the example you sent, the first two heights are necessary and the third is incidental.

    Good luck,
    jr

  99. AudiOxide says:

    Excellent Work!!!

  100. Michael says:

    How would you randomize the first image?

  101. MiD-AwE says:

    Jon,

    I love this, thank you. I have been watching for your answer to Simon R??nnqvist question regarding multiple slideShow’s on one page. Have you reached any conclusion? I am in great need of this information too.

    Thanks again.

  102. Alan Vien says:

    Hi Jon,

    I am new to this. I have tried to follow your instructions but the images are stacking one above the others.
    What did I do incorrectly?
    You can see it here.
    http://laseralliance.com/index.php?pg=wooden_letters
    Please help.
    Thanks.
    Alan

  103. Graeme says:

    Hi Jon

    Great piece of code, I’d also look forward to an answer on the multiple slideShow’s on one page, when you get a chance. Thanks.

  104. Alex says:

    Love your script!

    I’m trying to figure out how to pause the slide show and and show the caption on mouse over.

    The caption will be hidden on mouse out. I tried the code you gave as a reply to another commenter but can’t get it to work.

    Can you point me to a tutorial?

  105. Alex says:

    I figured it out!

    I have my slideshow in a list:

    <ul>
    <li><img src="img_1.jpg"><span>caption 1</span></li>
    </ul>

    On hover I pull up the caption and pause the slideshow with:

    var playSlideshow = setInterval( “slideSwitch()”, 5000 );

    $(function() {
    $(‘#slideshow’).hover(function(){
    $(this).find(‘span’).animate({bottom:’0px’},{queue:false,duration:500});
    $(‘#slideshow’).find(‘span’).addClass(‘showCaption’);
    clearInterval(playSlideshow);
    }, function(){
    $(this).find(‘span’).animate({bottom:’-60px’},{queue:false,duration:500});
    playSlideshow = setInterval( “slideSwitch()”, 5000 );
    });
    });

    Thanks Jon for your tutorial and explaining how to pause the slideshow. Thanks Timothy van Sas (http://www.incg.nl/blog/2008/hover-block-jquery/) for explaining how to show and hide blocks of content.

    One thing I need a little help with, in the css the span is set with display:none; to hide it by default and I use the addClass function to make it display:block; on hover. This causes the span to jump on the first hover. Any ideas on fixing that?

    note: this is a re-post because I made an error in the my last post and I added my fix for hiding the caption.

  106. z.Yleo77 says:

    wonderful ,,i like and i study..

  107. Julian says:

    hello-

    Fantastic little script. I’m trying to piece together a few things- mostly Alex’s solution whereby on hover the slideshow pauses and the caption appears yet I cannot seem to get it right- of course it may be because I know almost no javascript! Any guidance would be much appreciated!!

    Thanks.

  108. delta says:

    Thanks so much for this! Really simple and effective.

    Just one thing that I personally found: the last image would not fade back into the first one, it would just loop back to the first image without a fade. After some testing I placed the CSS _after_ the javascript/jquery and it worked perfectly!

    Great work JR thanks for this,

    cheers

  109. J says:

    So… Anyone have any luck implementing Alex’s solution that allows the pausing and display of a caption on hover… I can’t seem to get it…

  110. Faffy says:

    I tried placing the CSS all over the document like delta suggests and still cannot get the last image to fade into the first at the end of the loop =(

  111. Jess says:

    Thanks for this, it is easy to use and works great!

    But I am having a problem, I am trying to use it in the same page that has lightbox and it seems there is a conflict.

    How do you work around this issue?

    Thanks

  112. Jess says:

    Nevermind, I figured it out, in case anyone runs into this issue here is the code:

    function slideSwitch() {
    var $active = jQuery(‘#slideshow IMG.active’);

    if ( $active.length == 0 ) $active = $(‘#slideshow IMG:last’);

    // use this to pull the images in the order they appear in the markup
    var $next = $active.next().length ? $active.next()
    : jQuery(‘#slideshow IMG:first’);

    // uncomment the 3 lines below to pull the images in random order

    // var $sibs = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next = $( $sibs[ rndNum ] );

    $active.addClass(‘last-active’);

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }

    jQuery(function() {
    setInterval( “slideSwitch()”, 5000 );
    });

  113. kovi says:

    Hello,

    there is a problem, which I cannot solve… You can not use this slideshow nad LightBox at the same page – the slideshow will show only the first image, and there is no slideshow. can somebody help me with this? what can be the problem? thanks

  114. daft01 says:

    hi there, nice script. i am pretty well versed with js and started learning jquery one week ago and really like it, i wonder is there a real utility in preceding variable names with the dollar sign?

  115. Jon Raasch says:

    Hi Daft,

    The $ prefix on the jQuery variables is not essential by any means, I just use it to denote whether the variable represents a jQuery object rather than a plain variable. I don’t think it’s a jQuery standard but I know other people use that syntax as well.

    Thanks for reading,
    jr

  116. sagnik says:

    how puase / play slideshow .

  117. sagnik says:

    plz help and give an example of code.

  118. Jon Raasch says:

    Hi Sagnik,

    Playing and pausing the slideshow can be handled easily with the interval. Basically the idea is that you need to clear the interval to pause the slideshow and start the interval up again when you want to play.

    When you first start the slideshow, define the interval as a variable:

    var playSlideshow = setInterval( “slideSwitch()”, 5000 );

    Then when you want to pause the slideshow:
    clearInterval(playSlideshow);

    Finally, to start the slideshow’s cycling up again, just set the interval again.

    Good Luck,
    jr

  119. Rahul says:

    Impressive. Very nice jquery slide show.

  120. rs-flea says:

    hello there,

    im new to this jQuery game and was wondering how one could add links to the slideshow images?

    i simply tried adding the code to the html but then it made the slide run buggy.

    thanks for the great post :-) Cheers!

  121. Leelou says:

    Hello.
    I am new on this blog and I have just worked on the slideshow. It runs but I have just one a little bug. While slideshow runs, sometimes, there are quick acceleration of my images and sometimes it does flickers.
    I read posts ans I have added modifications you told about. But it doesnt run perfectly.
    Do you have any idea ?
    Thanks a lot.

  122. Grace says:

    Hello,

    I am also very new to the jQuerey game and was wondering the same thing. Is it possible to add links to the images and if so, how?

    Any tips are much appreciated.:)

  123. Jon Raasch says:

    Hi Grace and rs-Flea….

    I think I answered this before but may be getting lost in the comments. Basically, to include links around the images, first wrap each image in a link. Then everywhere in the CSS and Javascript that you see “IMG” change it to “A”

    Hi Leelou….

    It sounds like you need to set the first image to have the class “active” and then also make sure you have the opacity values defined in your CSS like so:

    #slideshow IMG {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    opacity:0.0;
    }

    #slideshow IMG.active {
    z-index:10;
    opacity:1.0;
    }

    Good luck everyone!
    Jon

  124. rs-flea says:

    Thank you for the response. We’re good to go :-)

  125. Jake says:

    This was a great read. Made perfect slideshow with a few modifications. And your simple setup made it really easy to add a thumbnail menu as well! Thanks for the tutorial.

  126. Cesar says:

    Great little script!!!!

    One question: If there is only 1 image… How can I tell the script NOT to fade a single image???

    Right now, the image disappears and then the same image re-appears with a fade in.

    Thanks!!!!!

  127. Mani says:

    I too am looking to run multiple instances of this on one page. I was able to do it by changing the #slideshow div to a .slideshow class. All works great EXCEPT that once all slideshows have cycled through their images, then only the first instance continues to cycle … the rest stay stagnant on the last image. I would LOVE help with this. Thanks!! =)

  128. Hi Jon,

    I have included this on my website but the top menu is going below the banner image. Do you suggest a work-around for it.

    Kind Regards,
    Khuram

  129. welshhuw says:

    Hi,
    Total noob at jquery and slideshows. Ive copy and pasted the coding but cant get it to work?
    Please can uou axplain in steps what i need to do?!?!
    1. Link to jquery-1.2.6.min.js file (Correct?)
    2. Link to the css file.
    3. Insert the HTML.
    4.???

    Thanks!

  130. Quinton Pike says:

    Very good little slideshow. Very minimal and very small source code sizing for fast loading.

    A++

  131. james says:

    Hi Jon,

    I love your slideshow app, but one problem if you could help me:

    How do I get it so the first image it chooses is random as well? I dislike setting one image as active and I tried removing that and it ends up just selecting the last image. Anyway to get it to choose the beginning image randomly as well?

  132. Kirk says:

    First of all, thanks for the simple and usefull script!

    I changed all “img” to “a” in code, as i want to link from slideshow to bigger images. But any idea why adding link to the first one (class=”active” anchor) prevents this first slide showing? After that it plays nicely, and links are working. The first link is working also, only it doesn’t be visible in the start.

  133. nico says:

    hi there,
    thanks for this nice script!
    i’m triyng to implement the pause on hover, but i really can’t‚Ķ
    would you so kind to make an example, like the one in the download, that has this function?
    that would be great!

    best regards, n

  134. Dimitar says:

    Hi am using your slide show and it’s grate but in the in the slide show I want the next image to be changed on click on image. Example I have 5 images in the slide show div. Bottom i have 5 thumbnails from the top 5 images that are in the slide show div. Now want I click on same picture in the slide show i want that image to be the $next in the function. Can you help me about this. Pleas replay me on my email ASAP pleas. Thanks

  135. percival says:

    I’m a rookie trying to spice up a friend’s website beyond the regular html/css. I typed the code into my page but nothing happens. Should I be linking the jquery-1.2.6.min.js file to my page? Is that a stupid question. Even though I can’t get this thing to work I SO appreciate your site. It’s a great intro to this stuff. Thanks!

  136. Riccardo Valsecchi says:

    dear,
    wonderfull, but how can I add a subtitle or a comment too on every image?
    I see for example that in your tutorial, with alt command, it works only for “slideshow image 5″ why?
    best

  137. ssk says:

    I like this great script.

    Is it possible to show the images in reverse order as well as forward order when click the previous and next buttons?

  138. Dan says:

    Hi Jon,

    I’m trying to use your slidehow for our school’s website. However as I am yet to brush up on my CSS layout techniques I’ve built it in tables. As soon as I place your code inside a table, the captions squash to the left and place one word on each line only. See the site @ edmontoncounty.co.uk…what have I done wrong?

    Many thanks!

  139. Casey says:

    Awesome Article!

    Sorry if this question has been asked before but was wondering if anyone could answer how we may be able to randomize the first slide with the class of (.active)?

    Even better… how would we be able to have it fade in at the beginning as opposed to it just being static when the page initially loads?

    Regardless / Much thanks for the tutorial!

  140. sorry, put html tags in my comment :p

    For the ones who had (like me) troubles with the first image that didn’t shows, but after the first interval everything is correct
    the most simple code:

    body

    replace with

    body onload=”slideSwitch()”

  141. Jess says:

    Hi Jon! Just wanted to say this script is awesome and works great! Thanks so much!

  142. Jo says:

    Hi Jon + all commenters,

    This is the simplest and easiest slideshow I have found. It works great, and I can pause/play awesomely. My issue is that I also need a pager. If I click on a link 1, 2, 3, or 4, I want $active to become the respective image.

    I am really unhappy with the idea of having to use another slideshow (like Cycle, which includes 4 JS files) to accomplish my goal. Any suggestions or ideas?

    Please help!

    Here is the code that I have used:

    function slideSwitch() {
    var $active = $(‘#mainBanner a.active’);

    if ( $active.length == 0 ) $active = $(“#mainBanner a:last”);

    var $next = $active.next().length ? $active.next()
    : $(‘#mainBanner a:first’);

    $active.addClass(‘last-active’);

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }

    var playSlideshow = setInterval( “slideSwitch()”, 5000 );

    $(function() {
    $(“#pauseButton”).click(function(){
    clearInterval(playSlideshow);
    $(“#pauseButton”).hide();
    $(“#playButton”).show();
    });
    $(“#playButton”).click(function(){
    playSlideshow = setInterval( “slideSwitch()”, 5000 );
    $(“#playButton”).hide();
    $(“#pauseButton”).show();
    });
    });




    1
    2
    3
    4

    PAUSE
    PLAY

  143. tryna says:

    Hi Jon,

    Thank you very much for your codes. This helps a lot! I have one question though, which was addressed by some users above. While my slideshow can be played perfectly, it appears kind of choppy. Is there any way to fix this and make it transits smoother?

    Thanks,
    tryna

  144. Mallory Green says:

    Thank you. Nice programming job example demo.

    I have just starting playing with your example. I found that jquery conflicts with mootools which is the basis of my slideshow and photo repository program I am writing. I am considering a switch from jquery to mootools.

  145. Chris says:

    Mani, you’ve probably solved the multiple slideshow problems you where having, but i’ll post my solution anyway. Its not a general solution, but specific to the slides i’m showing which are different sizes. Anyway …

    /*********************/
    /* css */
    /*********************/
    #photo-slides {
    float: left;
    height:134px;
    width: 200px;
    border: 1px solid #fc7000;
    }
    #logo-slides {
    float: right;
    height:69px;
    width: 152px;
    }
    .slide-show {
    margin-left: 6px;
    margin-right: 6px;
    padding: 1px;
    position: relative;
    }
    .slide-show img {
    position:absolute;
    top:1px;
    left:1px;
    z-index:8;
    opacity:0.0;
    }
    .slide-show img.active {
    z-index:10;
    opacity:1.0;
    }
    .slide-show img.last-active {
    z-index:9;
    }
    /*********************/
    /* html */
    /*********************/

    /*********************/
    /* modified js */
    /*********************/
    function slideSwitch(target) {
    var $active = $(target+’ img.active’);
    if ( $active.length == 0 ) $active = $(target+’ img:last’);
    var $next = $active.next().length ? $active.next()
    : $(target+’ img:first’);
    $active.addClass(‘last-active’);
    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }
    $(function() {
    setInterval(“slideSwitch(‘#frame-slides’)”, 3000 );
    setInterval(“slideSwitch(‘#logo-slides’)”, 3000 );
    });
    /*********************/

    Essentially doing the sameand changing the slideshow to a class. You apply the class to the container div but also give it a unique id. You then specify the #id when starting the slideshow.

    Also means, as you can see in the css, each slideshow can be individually styled.

  146. Brent says:

    Fantastic, brilliant. And thanks for writing back so much in these comments!!

    I was also looking for a way to add BUTTONS that could allow someone to step to a particular slide in the mix. I’m posting my solution because at least a couple of people asked for it above, and I wanted to try my hand (kind of a newbie with jQuery). Everyone please feel free to use and modify as you see fit.

    —— JavaScript / begin ——

    function slideSwitch( slideTo ) {
    var $active = $(‘#slideshow IMG.active’);

    if ( $active.length == 0 ) $active = $(‘#slideshow IMG:last’);

    var $next = $active.next().length ? $active.next()
    : $(‘#slideshow IMG:first’);

    $active.addClass(‘last-active’);

    // added “slideTo” variable to allow transition to a selected slide
    // defaults to null, but if it’s >= 0, it will use this index for “$next”
    var slideTo = ( slideTo+1 )? slideTo : null;
    if ( slideTo != null ) $next = $(‘#slideshow IMG’).eq(slideTo);

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }

    $(document).ready(function(){

    // hide all images except first to avoid initial flicker
    $(“#slideshow IMG”).css({opacity: 0.0});
    $(“#slideshow IMG:first”).css({opacity: 1.0});

    // use setInterval to traverse list
    var playSlideshow = setInterval( “slideSwitch()”, 5000 );

    // create buttons to move to specific slide
    var $slideButtons = $(“#slide-buttons a.slide-button”);
    $slideButtons.click(function(){
    // stop the slideshow, to keep it from trying to overlap our transition
    clearInterval(playSlideshow);
    // call the function using the index of the clicked button
    slideSwitch( $slideButtons.index(this) );
    // restart the slideshow
    setTimeout( playSlideshow = setInterval( “slideSwitch()”, 5000 ), 5000);
    });
    });

    —— JavaScript / end ——

    I added 2 lines into the “slideSwitch” function, and also added an argument. Outside that function, I added an additional jQuery object that finds “#slide-buttons” and its children “a.slide-button”, and gives them the power to switch to a given slide, using the index of that “a” within the DIV. See below for an example (drop it anywhere in your HTML).

    —— HTML / begin ——

    Button for Slide 1
    The 2nd Slide
    another one…
    last slide!!

    —— HTML / end ——

    As you can see, the tags could contain anything, so long as they have class=”slide-button”: so you could create thumbnails for the slideshow and use little images. Also you could further modify the script to highlight the button of the image you’re on…

    Another smart technique might be to use the DIV#slide-buttons as a caption that appears on hover over the slideshow.

    Cheers, and thanks again for your awesome and simple script.

    -Brent

  147. allan says:

    Hi,

    How do you change the z-index in such a way that the Nice Menu for drupal will not appear behind the images. If I change the z-index for active image will not work in IE. Please do give me ideas.

    Thanks

  148. Rick says:

    Ia m trying to setup two slide shows side by side and for the life of me I cannot figure it out… I know others have said they have achieved this, so could you send me a link to yous site with more than 1 going??

    Thanks

  149. Eric says:

    Hey does anyone have any problems with the text from the CAPTION not going away and duplicating itself on the next image?

  150. Eric says:

    PS I am using the script and code from the DOWNLOAD example 2

  151. Jon Raasch says:

    Hi Eric,

    My bad, if you are using a single-color background, try setting the individual panel divs background color to the same as that.

    Good luck,
    jr

  152. Eric says:

    Ah Good call! I am using transparent, so i will adjust those…Man this is so effective and simple! Best slide i have found really!

  153. Eric says:

    Jon,
    Are you talking about the pages background color and the #slideshow CSS?

  154. Eric says:

    I just cut n pasted the CSS from the example…I then changed the SLIDESHOW DIV bg_color to match the site and viola

    Weird, there was no diff. in the css I had but it now works! LOL

  155. Boogielee says:

    How do you center your slideshow?

  156. Love this slideshow but still having image flicker issues when the page opens. Both firefox and IE. Help please.

    http://www.bethanygilbert.com/new/new

    Thanks!

  157. Also should have said that you see it more when you go from another page back to home or portfolio.

    I tried a preloader set at display: none on top of the suggestions here and still can’t get it to work.

    Thanks,

  158. Eric says:

    BoogieLee
    What I did was wrap it in a div that centered it.
    But on the SLIDESHOW div, just give it a WIDTH and then set margins to 0 and auto:

    #slideshow {
    position:relative;
    height:350px;
    width: 500px;
    margin: 0 auto;
    }

  159. nazcar says:

    great. nice jquery slideshow tutorial

  160. allan says:

    I got the z-index problem. To make the menu appear on top just put a higher z index on the menu. Much way higher than we have here. Nice thanks you can view it here http://www.cocpo.org

  161. Blaine says:

    I can not seem to get the pause function to properly execute, I am clearly missing something in the code, if any one would be so kind as to assist it would be greatly appreciated, here is my code:

    function slideSwitch() {
    var $active = $(‘#slideshow DIV.active’);
    if ( $active.length == 0 ) $active = $(‘#slideshow DIV:last’);
    var $next = $active.next().length ? $active.next()
    : $(‘#slideshow DIV:first’);
    $active.addClass(‘last-active’);
    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }
    $(function() {
    var playSlideshow = setInterval( “slideSwitch()”, 5000 );
    });
    $(‚Äô#slideshow’).hover(function() {
    clearInterval(playSlideshow);
    },
    function() {
    playSlideshow = setInterval( “slideSwitch()”, 5000 );
    });

  162. Redlotus says:

    @ delta
    “April 1st, 2009 at 7:22 am

    I had the same problem.. using an external stylesheet. I put the css in the html doc below the javascript as you suggested and then it worked.

    Nice one!

    I guess the question is does this script work with an external stylesheet?

  163. Redlotus says:

    @ delta
    “April 1st, 2009 at 7:22 am

    Lol i see why it wasn’t working.

    #slideshow ing.last-active {

    ing.

    But it is working now and in an external sheet. Thanx Jon & posters.

    u rock my world.

  164. archie says:

    Thanks for posting this!!!!
    I do have a problem though.
    This script seems to be slowing down or controlling the speed of another js element being used on a page I am working on.
    I am using a slide.js on a menu (found at http://www.leigeber.com/2008/05/sliding-javascript-menu-highlight-1kb).
    Does any one know what is causing this conflict?
    Cheers
    Archie

  165. Ceri says:

    Hey Jon – I really liked this, the code so neat and to the point. Unlike so many other image faders/slideshows out there. However, like others, it still breaks when served up under an XHTML 1.0 Strict Doctype with an XML prologue (using application/xhtml+xml):

    Brief research suggests that jQuery is problematic because of it’s use of innerHTML – what are your thoughts?

  166. Binyamin says:

    Slideshow fading does not work on texts in TextOther text It shows one text under other.
    Do you have some resolution?

    JavaScript:
    function slideSwitch() {
    var $active = $(‘#slideshow div.active’);
    if ( $active.length == 0 ) $active = $(‘#slideshow div:last’);
    var $next = $active.next().length ? $active.next()
    : $(‘#slideshow div:first’);
    $active.addClass(‘last-active’);
    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);
    });
    }
    $(function() {
    setInterval( “slideSwitch()”, 2400 );
    });

    CSS:
    #slideshow {
    position: relative;
    }
    #slideshow div {
    position:absolute;
    z-index: 8;
    opacity: 0.0;
    }
    #slideshow div.active {
    z-index: 10;
    opacity: 1.0;
    }
    div#slideshow div.last-active {
    z-index: 9;
    }

    HTML:

    One
    Two
    Three

  167. Binyamin says:

    Again HTML:
    <div id="slideshow">
    <div class="active"><img id="slideimg" src="/images/slideshow-01.jpg" width="214" height="188" alt="Mother and Child in the Desert, 19X30" /><span id="slidetext">"Mother and Child in the Desert" 19X30</span></div>
    <div><img id="slideimg" src="/images/slideshow-02.jpg" width="214" height="188" alt="A Jerusalem Panorama, 25X35" /><span id="slidetext">"A Jerusalem Panorama" 25X35</span></div>
    <div><img id="slideimg" src="/images/slideshow-03.jpg" width="214" height="188" alt="Landscape, 50X25" /><span id="slidetext">"Landscape" 50X25</span></div>
    </div>

  168. Hi Bethany, did you try setting all but the active image to opacity:0.0 in the css?

    See comment 52

  169. Rob Wood says:

    Solved probblem now, sorry to have been a pain :)

  170. Binyamin says:

    Hi Patrick Cunningham,
    I did like you said – change active DIV to opacity: 0.0;
    but it still DOES NOT work – on slideshow the text is displayed one under other.
    Please help me to fix it.

    #slideshow div {
    position:absolute;
    z-index: 8;
    opacity: 0.0;
    }
    #slideshow div.active {
    z-index: 10;
    opacity: 0.0;
    }

    That slideshow with the text you can see in site http://www.rutiassis.com/en/home.html

  171. Alwyn Kotze says:

    Almost went mad because the pause on hover would not work.

    My solution was to put the hover code as follow:

    $(document).ready(function(){

    var playSlideshow = setInterval( “slideSwitch()”, 5000 );

    $(“#topbarouter”).hover(

    function() {
    clearInterval(playSlideshow);
    },
    function() {
    playSlideshow = setInterval( “slideSwitch()”, 5000 );
    slideSwitch();
    });

    });

    followed by the slideSwitch() function just below it.

    Works like a charm

  172. @Patrick

    Yeah. I did that. I finally gave up and went with a flash slideshow. I’m happy with it and my SEO is working great so oh well!

    Thanks for replying to my question though!
    Bethany

  173. Rob Wood says:

    @Chris – You posted a way of having mulitple images on one page, I have obviously pasted something wrong. Changed the containers to box1 and box2, changed from ID to Class…but have a missed something?

    If anyone can have a look, http://www.trytest.net/consult/website/

    I would be very happy :)

  174. Chris says:

    @Rick & Rob

    My solution for mutiple slideshows;

    http://www.moderneyewear.co.uk/test.html

    I will try to leave the above page active as long as possible. Hope it helps.

  175. Rob Wood says:

    many thanks for that…although getting jumping images now!!! :) If anyone gets moment…http://www.trytest.net/consult/website/index.php thanks :)

  176. Chris says:

    My solution has been updated and (seems) to work for all html elements, img, a, div, etc, although not thoroughly tested!

    Example still at http://www.moderneyewear.co.uk/test.html

    And many many thanks Jon for a great and simple solution to slide shows (and my intro to jQuery).

  177. Keith Davis says:

    Can’t add anything to the technical discussion, but I can say that this is just what I’ve been looking for.

    I’m looking to rotate a number of images in a web page header and have found a few solutions, all of which leave you with a problem when javascript is deactivated.

    This solution addresses that problem.

    Quick question… what is the difference between example 1 and example 2 in the download? Probably obvious but I’ve not spotted it.

  178. Sincklation says:

    thanks for the information, i need to solve this quickly so this code was very usefull, i made a little modification so no need to put css code and you can configure transition time and the effect time.

    http://sincklation.com/2009/08/transicion-de-imagenes-o-slideshow-con-jquery/

  179. kelly says:

    THANK YOU so very much for your work on this and your generosity in sharing. This is *precisely* what I was looking for, and the *perfect* solution to my slideshow needs for a new page.

    Muchas gracias,
    kelly.

  180. Keith Davis says:

    Just set it up in a header graphic.
    Looks brilliant, just what I wanted.
    I may never understand javascript, but with plugins like this… I’m not bothered.
    Thanks a million.

  181. harshit says:

    Great script man !!! Can I use this in the background of td or div=. If it is possible then that would be great.

  182. SunJoo says:

    Great script – easy and does the beautiful job.

    Thanks again for the great work.
    Cheers

  183. Patrick C says:

    Thanks for this tutorial, worked an absolute treat.

    I’ve been using your code with Drupal to create a slideshow based on views. There is actually a module that already does this called Views Slideshow, however the transition between images is much smoother with your code, and it is a lot more lightweight.

    Thanks again!

  184. Paco Valverde says:

    I needed it to rotate continuosly so I added the following:

    var $last = $(‘#slideshow IMG:last’);
    var $first = $(‘#slideshow IMG:first’);

    and before the line:

    $next.addClass(‘active’);

    I added this if clause:

    if ($last.hasClass(‘active’)){
    $last.removeClass(‘active’);
    $first.addClass(‘active’);
    };

  185. Jon Raasch says:

    Hi Paco,

    Thanks for sharing, but the script handles that already, that’s the purpose of the:
    var $next = $active.next().length ? $active.next()
    : $(‘#slideshow IMG:first’);

    Best,
    jr

  186. Eyveneen says:

    Hi Commentors and John,

    Everyone loves this slideshow and I guess everyone has their preferences. I added a button to advance the image. Here is the code that I used I hope it is permissable:

    the css:

    #samples {
    position:relative;
    width:500px;
    height:435px;

    }

    #samples IMG {
    position:absolute;
    top:-20px;
    left:200px;
    z-index:8;
    display:none;
    }

    #samples IMG.active {
    z-index:10;
    display:block;
    padding:45px;
    border:solid 2px #fff;
    background-color:rgb(203,179,79);
    }

    #samples IMG.last-active {
    z-index:9;

    display:none;
    }

    the jQuery:

    $(‘#activate a’).click(function(){

    $(‘#desc’).css(“display”,”none”);

    var $active = $(‘#samples IMG.active’);

    if ( $active.length == 0 ) $active = $(‘#samples IMG:last’);

    var $next = $active.next().length ? $active.next()
    : $(‘#samples IMG:first’);

    $active.addClass(‘last-active’);

    $next.css({opacity: 0.0})
    .addClass(‘active’)
    .animate({opacity: 1.0}, 1000, function() {
    $active.removeClass(‘active last-active’);

    });
    });

    the html:

    Activate

  187. Daniel says:

    First off, thanks for your work on this – great plugin. I’m already using it just for images, but now I’m trying something more complicated, and I’m running into problems…

    I’m trying to set up a page to slideshow divs, but the divs have other divs inside of them. I don’t know that much javascript, but I’m guessing that’s what’s breaking it here, as the script seems to want to cycle through all divs under my main slideshow div. If so, is there any way to address this besides using tables to lay out my slideshow divs?

    If that shouldn’t be causing a problem, I’ve broken something else, but this is just my best guess. :) Thanks.

  188. Daniel says:

    Well, sorry to post and then answer my own question. I replaced my inside div with a span set to disply:block, and that seems to have resolved the troubles.

  189. brion says:

    great stuff

  190. jq says:

    I’ve set up the jQuery Slideshow on a page that’s also using a LightWindow modal box and there seems to be a conflict between the javascript libraries for the two.

    Lightwindow uses: effect.js, lightwindow.js, prototype.js and scriptaculous.js.
    Slideshow works fine if these references are removed from the head.

    Has anyone else run into this problem? Anyone have a fix?

  191. jq says:

    UPDATE: I found a good solution to the library conflict. Dropped Lightwindow and substituted FancyBox which is based on jQuery. Seems to work well.

  192. Catherine says:

    How can I have links show which image the visitor is currently viewing and also to skip through images. Example:

    Back Image1 Image2 Image3 Forward.

  193. vgan says:

    Jon,

    Thank you so much for this simple and elegant code, I spent hours and hours wrestling with different plugins and could not get anything to do what I needed until I found this.

    I’m calling the slideSwitch() function without a timer within another jQuery function controlling menu content.

    This advances one picture at a time in sync with menu content fading in and out, works beautifully!

  194. Jon Raasch says:

    Hey jq, glad you solved your conflict problem, but in case anyone has the same issue and does NOT want to drop their previous library, I believe the conflict can be resolved by changing the $ to jquery throughout the JS, for instance jquery.(function() {}); Of course wherever we’ve defined JS variables that use the $ as shorthand, you can leave these alone, ($next and $active)

  195. Sam says:

    Simple and elegent!! You are the best, mate.

  196. Jon, thanks very much for this great little tutorial, love how simple it is. I’m busy implementing it on a client’s site at the moment.

  197. Hamza says:

    Hi,
    Thank you for posting such a good solution for cross fade.
    It is so smooth> I am not very well at JQuery and it was so simple that i could understand it.

    I have few questions:

    - How can we put Pause and Auto Play buttons in this solution?
    - How can we make different blocks of cross fade.
    E.g, a block may contain 4 images and those images will rotate with in that block, The second block also may contain many images and those images will be rotated with in that block. And these two blocks will also do cross fading with each other.

    Is it possible? If yes, please suggest some solution over here.

    Thank you
    Hamza

  198. kels says:

    Is it possible to make is select the first div without having the active class? I have all the images being loaded in a PHP array and if I give it a class of active it gives all the images the active class and screws the thing up. Thanks.

  199. nlx says:

    Nice but it would be really cool if the slideshow itself appear in a FadeIn…

  200. kels says:

    I figured out how to make it work for me.

    Change:
    —————
    $(function() {
    setInterval( “slideSwitch()”, 5000 );
    });

    To:
    —————
    $(function() {
    slideSwitch()
    setInterval( “slideSwitch()”, 5000 );
    });



Comments are closed.