Need some help?

I'm usually available for small jobs or problem solving with jQuery or css, at reasonable rates. Just get in touch.

Web Hosting

We recommend Clook for web hosting. UK based, great service and great value.

Buy me a drink

If you've found this useful, particularly for commercial projects, you might consider making a small donation.

Simple jQuery image crossfade

I wanted a simple jQuery crossfade effect for an image cycler last week, and surprisingly couldn’t find anything suitable. So I ended up writing my own, and here it is. Tested in IE6/7/8, Firefox 3, Chrome, Opera 9/10, Safari 4, all on Windows XP, IE8/9, Firefox, Chrome and Safari 5 on Win 7, Safari 5 on Mac OS X/Snow Leopard, and Android Browser and Dolphin on Android.

The demo

Hoverfly on a green leaf Fly on a pink flower Insect on a leaf Fly

This basic demo page will show you exactly what’s needed.

The code

You need the following basic html:

<div id="cycler">
<img class="active" src="image1.jpg" alt="My image" />
<img src="image2.jpg" alt="My image" />	
<img src="image3.jpg" alt="My image" />	
<img src="image4.jpg" alt="My image" />		
</div>

Here’s the necessary css – just to show the z-index and positioning – you’ll need to add some more to position as required. Depending on your layout you may also need to set the height and width on #cycler to match your images:

#cycler{position:relative;}
#cycler img{position:absolute;z-index:1}
#cycler img.active{z-index:3}

And here’s the javascript:

function cycleImages(){
      var $active = $('#cycler .active');
      var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first');
      $next.css('z-index',2);//move the next image up the pile
      $active.fadeOut(1500,function(){//fade out the top image
	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
          $next.css('z-index',3).addClass('active');//make the next image the top one
      });
    }

$(document).ready(function(){
// run every 7s
setInterval('cycleImages()', 7000);
})

The logic

All the images are loaded with the page and positioned absolutely on top of each other, all with z-index=1. One image is initially set with a class of “active”, which is positioned on the top of the stack with z-index = 3.

Then, using jQuery, I’m identifying the active image, and then the next image down. I’m doing this via the jQuery .next() method. If there isn’t a next image – if we’re at the end of the images – I’m selecting the first image instead using .first().

Now, once I’ve identified the next image, I’m assigning z-index=2 to this so it’s the second image down in the pile – and hence is visible when the top image fades out.

Then, I’m fading out the active image. When this completes there’s a few things to do. First, I’m setting the z-index of the active image (now faded out) back to z-index=1. Then, I’m reversing the fade by using the show() method. It won’t be visible now because of the z-index. Finally, I’m removing the active class. Effectively, I’m putting this image back into the bottom pile.

Nearly there. Then, with the next image, which is now on top anyway, I’m assigning z-index=3, and then adding the active class to this image.

Finally, all of this code is sitting in a function which I’m calling every seven seconds via setInterval().

Responsive version

Making this responsive (without media queries, which is what this page uses) is pretty striaghtforward. The trick is to use a ‘base’ image which is not absolutely positioned to set the dimensions of the cycler and then apply a max-width to #cycler. The base image is then cloned and the cloned version is faded in and out. Have a look at the responsive demo here.

Help! It doesn’t work

If you hit problems, start off by looking at my beginners’ guide to debugging jquery. Most of the problems encountered by users are listed here.

Can I use this on my site?

Probably. See my policies on using code from this site.

Variations on the basic crossfade

Here are a few variations, mostly built in response to questions or comments on the basic code. View the source to see how they’re done.

Cycle through images once and then stop

Multiple cyclers on a page (with a common periodicity)

Multiple cyclers on a page (with different periodicity)

Multiple cyclers with slideshow controls

Cycler with variable timings

Cycle divs instead of images

Superimpose text on the cycler

Cycler with fadeout transition

Crossfade images, no slideshow

Gallery with thumbnails

Tags:

377 responses to “Simple jQuery image crossfade”

  1. Simon says:

    Start with this version of the slideshow which doesn’t run automatically.
    The transition here is triggered by a click:

    $('.cycler_controls a.page').click(function(){

    So just amend the trigger so it runs on a hover event instead of a click.

  2. Amit says:

    How to show images one after the other on hover (Consider several images to be displayed and display them one by one. The first image is displayed and when you hover over it, and it should be fade out and another image to fade in. Then the second image to fade out on hover and the third image to fade in, and so on.

  3. Luis Lara says:

    thanks a lot.

  4. Jackie says:

    Thank you for this great solution. I’ve tried several different solutions but none worked smoothly (or at all). This is simple, neat and well explained, which means it’s also then very easy to adapt. Great work.

  5. Simon says:

    Hi Mike, it’ll work OK with just two images. The ususal issue is that you’ve got soemthing else in your html which is beig treated as the ‘last’ image in error – hence the bumpy transitions. Best way to track this down is to have a look at the html in developer tools. You can see the javascript fading the images in and out and this should give a hint as to what happens after the final image.

  6. Mike says:

    Firstly, so impressive that 9 years later you’re still giving support on this code! Thank you!

    Is there a minimum number of images this needs to work?

    Im using the “Multiple cyclers on a page (with different periodicity)” version of the code in a 2×2 grid (each cycler has a different number of images), however the final image fades out to nothing, and then the first image “jumps” back instead of transitioning.

    Any idea’s why this would be happening?

  7. Simon says:

    Hi Lee
    Impossible to tell without the code. Have you loaded jQuery (just once)? Are you targetting the correct element with your javascript? If you view the javascript console from your browser (Ctrl+Shift+I in Chrome, Ctrl+Shift+K in Firefox) that may give you a clue.

  8. Lee Cornell says:

    Hi Simon, For some reason the three (same size) transparent logos I’m displaying in the html:

    folder, isn’t actually rotating although images are there on top of each other. CSS and JS file are in appropriate folders… What’s needed to trigger rotating banner…

  9. Simon says:

    Hi Scott
    You should be able to do this by combining the responsive version with this code for multiple sliders.
    Simon

  10. Scott says:

    Nice work Simon. I have used your code on a couple of sites without problem but I now want to use the code for a responsive version but with two cyclers on the same page. Cannot get this to work since the responsive script really needs an id but more than one cycler uses a class instead. Any suggestions would be appreciated.

  11. Simon says:

    That sounds like an issue with your css. Either wrap your images in a container which has a fixed height, or (better) use the responsive version.

  12. Wendy says:

    Hi, Simon.

    When I add your cycler, the content beneath the cycler becomes hidden by the image(s). How can I prevent this from happening?

    Thank you!

  13. Simon says:

    Regina, not quite sure what you’re trying to achieve. If you can post a link to your page or your code I may be able to help.

  14. Regina says:

    hey Simon. I have problem in editing your script to mouse hover multiple crossfading images. Do you mind to show me how?

  15. Simon says:

    Henk
    You don’t need to change the javascript at all. It will cope with however many images you have in your html.

  16. Henk says:

    Simon….

    Thank you for this code you created. I have added this into a site im building but simply CANNOT figure out how to add more images and make it work?? I have 11 images

    #cycler img{
    position: absolute;
    z-index: 1;
    }

    #cycler img.active{z-index:12}

    …..

    function cycleImages(){
    var $active = $(‘#cycler .active’);
    var $next = ($active.next().length > 0) ? $active.next() : $(‘#cycler img:first’);
    $next.css(‘z-index’,11);//move the next image up the pile
    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).show().removeClass(‘active’);//reset the z-index and unhide the image
    $next.css(‘z-index’,12).addClass(‘active’);//make the next image the top one
    });
    }

  17. MaryAnn says:

    Thank you! Thank you! Thank you! I’ve been searching everywhere for a simple cross-fading slideshow and haven’t found one until now that works properly!! You are awesome!!

  18. Simon says:

    Joe
    Put the images in a div with a background colour, position your images as required within the divs, then rotate the divs as in the example below.

  19. Joe says:

    Site might not be live as I’m developing it as we speak. Anyway, great solution, however it requires all your images to be the same size….the larger images peek out from the “pile” so to speak. I’m trying to use this as the landing page on my personal photo site, and I will have all different sizes/orientations of images.

    Any thoughts on a “masking” element or perhaps using transparency/opacity to show/hide images?

  20. Mike says:

    Yes, yes, yes, I got the right line, and the “first” to “last” change, but somewhere in the article or a comment was the word “reverse or reversing”, anyway, I could only think of “reverse”, PREV was no where to be found in my brain, wow, you’re a genius — thanks so much.

  21. Simon says:

    Mike, Can’t say I quite understand why you’d need to do this, since the user won’t know the order of the images. However…
    You just need to change the code which identifies the next image to show, so that it looks at the previous, not the next image in the DOM. You need to update this line:

    var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first');

    to this

    var $next = ($active.prev().length > 0) ? $active.prev() : $('#cycler img:last');
  22. Mike says:

    Hi Simon:
    When cycling divs instead of imgs, with active is assigned to the last, or the div around the 4th image, how can I reverse the order, so that it cycles from 4th, 3rd, 2nd to 1st image and keeps repeating. So it cycles just like normal, except in reverse order. I’m trying to use .reverse() with no luck. Thanks so much, your site ROCKS.

  23. Simon says:

    Todd
    Thanks for your kind words. You should be able to just change the javascript so the controls fire on .mouseover() instead of .click(). Note however, that this will render the controls unusable on a touchscreen.

  24. Todd Wheeler says:

    Hi Simon,
    You’re crossfade script performs so well that I keep going back to it for the smooth, reliable image crossfade transitions.

    I’m trying to activate the crossfade across 3 images upon hovering over the controls, instead of after clicking on the controls. Additionally, I would like to apply a hover effect on the controls themselves, as seen here (and therefore, remove the “1 2 3” controls):

    http://userpages.bright.net/~toddw/css3-rollover/crossfade2.html

    You’re so generous in helping the many people shown here, so please let me know if I can send you $, Β£, or €!

    Thanks and regards,
    Todd

  25. Simon says:

    You should just be able to insert an image tag in the html when creating the controls. Have a look at this example to see how the thumbnails are inserted.

  26. Hi Simon,

    Thank you for such a great script. I think this is the best and number 1 script i ever found in the internet. I have 1 question to ask here; how do i change the slideshow control to image button instead of text. I tried to change it to html tag but the script wont load… Can you help me with this? Thank you so much Simon.

  27. Thank you so much for your help, Simon.
    Yes, it works now. I wouldn’t even guess that was the culprit.

  28. Simon says:

    Your other css is interfering. Get rid of this:

    .hovereffect img {
        display: block;
        position: relative;
        transition: all 0.35s ease 0s;
    }

    and the transtion is smooth.

  29. Hi, Simon. It’s been a long day for me trying to figure out how to make a simple fade thumbnail when it seems to be SO simple. I tried out your code and it’s ‘kinda’ work, but the problem is that the fading animation is not smooth. You can see it here: http://andrewnovialdi.com/anw-website-test/index.html
    It’s in the cherry image one. And I’m looking to apply this to more than one thumbnail. I desperately need your help. Thanks!

  30. David says:

    Thanks Simon!

  31. Simon says:

    Check your console for errors. Have a look at this line in particular:

    var active $('#banners .active');
  32. Nerijus says:

    Hi Simon,

    I have a issue with code, and don’t know how to fix it, mabie you could help me ?
    This is my HTML5 code: http://pastebin.com/WG81WUMQ
    This is my CSS:http: http://pastebin.com/pzXqKzyu
    This is my JavaScript code: http://pastebin.com/9gbJsRfc

    The problem is that i see only one image(what is good) but that image don’t swap with others two.

  33. Simon says:

    David
    The problem with your page is that the cycler has no height, as it uses position:absolute, so doesn’t push the footer down. As your page is responsive, you need to use a single image set without position:absolute at the bottom of the image pile (see here). This will give your slideshow some height.

  34. David says:

    Hi Simon. Top work on responding to all these posts. You deserve a medal! Anyway I had a good scan through but couldn’t find solution relating to my particular issue. I think the problem is related to “position: absolute;”. In effect the slideshow isn’t taking up the space it should on the page and is therefor hiding content underneath (i.e. the footer). Here’s the page where it’s happening:

    http://www.sle.co.uk/products/life-support/ventilators/sle6000b

    I’m not much of a coder at all but I did fashion a workaround of sorts by placing a ‘blank’ gif with nothing in it just below the slider, which kinda works (http://www.sle.co.uk/products/life-support/ventilators/sle6000h) but I’m sure there’s a better solution.
    Also I’d like to add some forward/back arrows and nav buttons but I think there’s a link somewhere on this page showing how to do that right?

  35. Simon says:

    That demo does fade the entire iframe.

  36. RastaPopuloS says:

    Ah thanks you but i don’t want that the content of the frame fadeIn/fadeOut, i would like that the whole iframe fadeIn/fadeOut πŸ™‚

  37. Simon says:

    Have a look at this demo.

  38. RastaPopuloS says:

    Hi,
    I made the same thing with divisions instead of pictures and it works. But when i want to fadeIn/fadeOut an iframe, it doesn’t work, it justs display/hide the iframe without any animation.
    Can you help me? :/
    Ty

  39. Simon says:

    Works now. Firefox never batted an eyelid….

  40. 14k says:

    Google Chrome

  41. Simon says:

    I don’t see a console error on my page. What browser are you using?

  42. 14k says:

    For some reason , it doesn’t work ( in your script ) . It gives the ‘Uncaught SyntaxError: Unexpected token =’ error in console …

  43. Simon says:

    Yes, have a look at this example. You can see how the previous and next buttons work in the script and adapt to your needs.

  44. 14k says:

    Hello Simon,

    Thank you for the script , it works just awesome .
    I have one question , though . Can a previous/next button be implemented here? I tried few things but couldn’t make it …

  45. Simon says:

    The images not stacked up is definitely missing css. If only the first image fades then there’s either something wrong with your javascript or with your html.

  46. Mary says:

    I copied and pasted everything exactly in the places they need to go.

    it works because the image fades. But only the first image fades. The 2nd image isn’t stacked underneath the 1st image and loads directly beneath it.

    Help?

  47. Simon says:

    It looks like that because the script doesn’t start until all the images have loaded on the page. You could set the first transition to run more quickly than subsequent ones if you want, by using a different (shorter) delay for the first image.

  48. Charles says:

    Hi Simon, it seems that the script ‘waits’ during the first interval and only kicks into action during the second one. Can it be made to start during the first interval?

  49. Simon says:

    You can use .index() to get the zero-based index of the current active image.

  50. Tobi says:

    Yes, frames is a thing I would strictly avoid.
    But my problem is: How can I get the current position of the slider and store it in a cookie?

    On your slider I don’t see a loop where I can get the index to store. πŸ™

  51. Simon says:

    I certainly wouldn’t separate the header from the rest of the page – that requires using frames and is definitely not recommended. You could store the current frame in a cookie and update this every time the slideshow changes. Or, assuming that all your intra site links are in your menu, you could add a query string to the link URL when it’s clicked, which is then picked up on the target page and used to set the current image.

  52. Tobi says:

    Hi Simon,
    I just want to add the cycler on my page as a banner slideshow. The header is on every page I click on my page.
    Everytime time I click on a link the whole page is refreshed. At the moment I can’t seperate the header part (where the banner slideshow should be) from the other part.

    Do you a solution how can I get the current position of the slideshow and save it. After the reload I can get the position and start from there and not from the beginning.

    I thought of using jcookie and save the position on every change event. But my problem is: How can I get the current position from this? I don’t see any for loop or any equivalent. Or do you have another idea instead of using cookies?

    At the moment I use your basic example and it work very well for me.

  53. Bob says:

    Thanks Simon, that was just what I was looking for.

  54. Simon says:

    Hi Bob
    Have a look at this demo
    Here the approach is to make the function recursive and set a longer timeout at the end of the cycle.

  55. Bob says:

    Hi, I found your script and want to use it to show 4 pictures but I need it to pause for about 5 seconds after the last one, before it starts the rotation again. Is there any way to do this? It’s probably something simple but I’m new to this so I’m baffled.

  56. Simon says:

    Hi Charles
    I suspect your problem is that the rel attribute is text, and so you’re passing a text argument instead of an integer argument to fadeOut(). Have a try with:

    fadeOut(parseInt($('div.active').attr('rel')))
  57. Charles says:

    Thanks for a great page, with a real cros-fade (there are many pseudo cross-fades around).
    I adapted your code to use divs and to include labels, which works fine.
    I added rel attributes in the html to set different lengths of time for the fades (the fades themselves, not the time between). Using console.log it seems everything works as it should (the various fade lengths are shown), but the actual fades appear to all have the same speed. Must be something embarrassingly simple, but I have no clue, and I am sure you do!

    function cycleImages(){
    var $active = $(‘#cycler .active’);
    var $next = ($active.next().length>0)?$active.next():$(‘#cycler div:first’); $next.css(‘z-index’,2);
    console.log(‘Fade length: ‘+$(‘div.active’).attr(‘rel’));
    $active.fadeOut($(‘div.active’).attr(‘rel’), function(){
    $active.css(‘z-index’,1).show().removeClass(‘active’); $next.css(‘z-index’,3).addClass(‘active’);
    });
    }
    $(document).ready(function(){setInterval(‘cycleImages()’, 4000);})

  58. Simon says:

    Yes, just wrap the image in a tags, and fade the them instead of the image tags. Use the div example to help you sort the javascript.

  59. James says:

    This really useful, thanks for sharing this! One question though, is there a way to link every image to something?

  60. Simon says:

    Steve
    The approach I’ve taken to make this any of these responsive is to place another image underneath the stacked images, which is NOT positioned absolutely. It then reacts to the viewport size and takes all the other images with it, as it were. Have a look at the demo here.

  61. Steve says:

    Thanks again for your help. I was able to get it the combination to work last night, though I still haven’t been able to get the positioning stuff to work the way I want. I just never know which divs/elements to assign the different formatting properties to. Now I’m going to try to make it responsive.

  62. Simon says:

    You should be able to combine these two examples to do what you want. To centre your thumbnails, set display:inline-block on the thumbnails and text-align:center on your containing element.

  63. Steve says:

    Thanks so much for this valuable resource. I can’t figure out on my own how to do the crossfade images with thumbnails (no slideshow) with multiple cyclers on the page. I’m trying to do a gallery where each main image (cycler) has several different variations (the thumbnails). Also probably an easy positioning thing that I’m just mistune, but how would I center the thumbnails under the main image?

  64. Simon says:

    That sounds like your css is not being parsed correctly on the Samsung. Have a try checking your css on the validator first off.

  65. Timo says:

    Your script works fine in the browser on my computer. However on my mobile Samsung device the different pictures appear among each other (making a list of images), instead of covering each other on the same position. Why is this and how can I avoid this?

  66. Simon says:

    Yes, take a look at the different variation examples listed above.

  67. Joey says:

    I love this and have added it to a site I’m working on but have now bee asked to add arrows and dots at the bottom so that people can scroll through the images themselves if that want. Is that possible?

  68. Simon says:

    Difficult to answer. It might be more useful to identify things you want to do and see how javascript,jQuery or one of the other libraries might help. I’ve yet to come across something that jQuery doesn’t cover, with the possible exception if interacting nicely with svg elements – for which the d3 library offers some advantages.

  69. Alan says:

    Hi Simon –
    I’ve been working on javascript and recently, jquery. I’ve got a problem with a tweened photo sequence which your code will hopefully solve. However, I have a more general question. Your code solves a fade-in/out need and that will help me. But, where can you actually find out all the practical things that it is possible to do with jquery. I keep wondering: How can you fully use jquery if you don’t know all the things it can actually do? Is there a list somewhere?
    Thanks – Alan

  70. Simon says:

    That certainly sounds possible for the cause. If so you can refine your jQuery selector so it only targets the absolutely positioned images. Or, possibly, you don’t have the active class set on an image. If you view the html in Firebug while the fade out is running that might give a clue as to the issue as well.

  71. Tim Dawson says:

    Hello Simon,
    Thanks for your response. I got around the varied number of images (if I recall) by using SASS. But it’s all hidden away in Git and I’m not going to dig it out to check. It did make it horrendously complex to maintain (probably my fault, not enough comments), and I’m much happier with the JS approach, particularly using divs with all the text wrapped up with the image in one fade.
    Right now I’m having a problem with a jump between the first image to show (the last to load) and the next one. After that they fade nicely and second time through is fine. I don’t have that problem in the test page (URL above) so I’m looking for the difference. It’s probably because the first image to load is the ‘static’ one, and it would be the second to show but doesn’t as it has ‘opacity: 0;’

  72. Simon says:

    Hi Tim
    Yes, the limitations of css3 is that you need to set the animations for a fixed number of images, whereas javascript is a bit more flexible and a lot simpler, and that’s ALWAYS a good thing!

    For responsive designs I have used a very similar approach to that you describe, with two versions of one image, one position :static which sets the dimensions, and the other position:absolute, with all the absolute images on top of the static one which is consequently never visible. See demo here.

  73. Tim Dawson says:

    Thanks for this. I had created an animation in CSS3, only to find it didn’t work in IE11 (though i believe it should have done so).
    For a large banner image where I can’t set a height (responsive design) I have loaded one image with ‘position: static’. This works, but that image doesn’t participate in the animation. Is there a better way ? NB: The images have associated text, so I have used divs containing both image and text. Much easier to handle than doing it all separately in CSS.

  74. Ernie says:

    I just wanted to add my thinks to the hundreds of responses above. Much appreciated.

  75. Simon says:

    Give #cycler an explicit height, or take a look at the reponsive demo on this page.

  76. victor says:

    im trying out your cycler, but theres a div under it suppose to be below it.

  77. Aggie G says:

    Hi Simon,

    Fantastic clear simple js – thank you!

    I’m using the cycler with timings – how do I add a pause resume button to this code?

    Thanks for your help.

  78. Michele says:

    Thank you for this brilliant, essential code snippet, I’ve be searching long for such a simple and comprehensive piece of code!
    In order to make it work on WordPress, I’ve embedded the javascript and the css using WP’s wp_enqueue_script and wp_enqueue_style functions, respectively.
    Also, in order to make the image exactly one underneath the other, I had to modify the css as:
    [pre]
    #cycler{
    position:relative;
    }
    #cycler img{
    position:absolute;
    z-index:1;
    top: 0px;
    left: 0px;
    }
    #cycler img.active{
    z-index:3;
    }
    [/pre]
    Without thte top: 0px and left: 0px commands the images won’t stack up correctly, and they’ll be displayed one under the other in sequence. Hope this helped!

  79. Simon says:

    Hi Craig
    Easiest to change the ‘endless slider’ variant I think. The html should be unchanged. Position the arrows below the images by amending the css, remove the display:none setting on them and remove the last line of the js which starts with:

    $('#endless_slider').hover

    If that doesn’t make sense post back.

  80. Craig says:

    Hello Simon, how can I add visible ‘back’ and ‘forward’ buttons to either your ‘fade out transition’ demo or the crossfade with pause variant please? Both beautiful, btw. I’ve seen http://www.simonbattersby.com/blog/jquery-endless-slider/ which is very close to what I’m looking for except that it works best with a mouse. I need the buttons left and right of the image (or under) and always visible. Sorry if it’s a dumb question.

  81. Simon says:

    What you want to output to the console is $active or $next:

    console.log($next);

    This will show the $next element in the console window – which may give a clue as to where the problem is.

  82. Mandy says:

    I changed the console.log code because I noticed I hadn’t put the inverted commas in (I’m very new to this) and now have this code:

    function cycleImages(){
    var $active = $(‘#cycler .active’);
    console.log(‘active’);
    var $next = ($active.next().length > 0) ? $active.next() : $(‘#cycler img:first’);
    console.log(‘next’);
    $next.css(‘z-index’,2);//move the next image up the pile
    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).show().removeClass(‘active’);//reset the z-index and unhide the image
    $next.css(‘z-index’,3).addClass(‘active’);//make the next image the top one
    });
    }

    $(document).ready(function(){
    // run every 7s
    setInterval(‘cycleImages()’, 7000);
    })

    which out puts this for every image:

    active localhost:397
    next localhost:395

    It continues to output that even though the images don’t change

  83. Simon says:

    If it’s going through the first cycle and then breaking it’s almost certainly a problem with what happens at the end in how you’re identifying the first image. Conceivably there are other images that your code is finding that shouldn’t be cycled, and the code is moving on to them, or it’s unable to find the first image again.

    It’s hard to be more definite without seeing your html – if you can post a link I’m happy to take a quick look. If you can’t post a link then look at using the console and print the value of $next out to the console. That should help you identify the problem.

  84. Mandy says:

    I love this but it I don’t seem to be able to get it to work properly. It’ll cycle through the images then after it’s done it once it jumps to the next one then stops completely. I’ve looked at what’s happening and it appears that it stops adding the ‘active’ class after the first cycle πŸ™

    This is how I’m using it:

    #cycler{position:relative;width:1000px;height:292px;}
    #cycler div{position:absolute;z-index:1;background-color:white}
    #cycler div p{position:absolute;top:100px;right:385px;color:white;margin:0;}
    #cycler div.active{z-index:3}
    #cycler img{display:block}

    function cycleImages(){
    var $active = $(‘#cycler .active’);
    var $next = ($active.next().length > 0) ? $active.next() : $(‘#cycler img:first’);
    $next.css(‘z-index’,2);//move the next image up the pile
    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).show().removeClass(‘active’);//reset the z-index and unhide the image
    $next.css(‘z-index’,3).addClass(‘active’);//make the next image the top one
    });
    }

    $(document).ready(function(){
    // run every 7s
    setInterval(‘cycleImages()’, 7000);
    })

    The slick choice

    For the extra mile

  85. Caitlin says:

    Thank you for your simple, easily understood, very flexible, slide show.

    (website still in markup stage or I’d give you a web address)

  86. Simon says:

    It’s as I suggested then, really. You want to be able to vary the .delay(500), so you could pass in a parameter to your cycleImages function:

    function cycleImages(ccontainer,delayTime){....
    ....$next.delay(delayTime).fadeIn()....

    or read it from data stored against the element by javascript ($(‘#myElement’).data(‘delayTime’,500)), then:

    ....$next.delay(ccontainer.data(delayTime)).fadeIn()...

    or just

    if(ccontainer = $('#myElement') delayTime = 500;
    else delayTime = 1000;
    $next.delay(delayTime).fadeIn()...
  87. Axel says:

    Hi Simon,
    thank you very much for answering. I am not familiar with javascript or jQuery. This is what I am using:

    function cycleImages(ccontainer){
    var $active = ccontainer.find(‘.active’);
    var $next = ($active.next().length > 0) ? $active.next() : ccontainer.find(‘img:first’);
    $next.css(‘z-index’,2);//move the next image up the pile

    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).removeClass(‘active’);//reset the z-index and unhide the image
    $next.delay(500).fadeIn(1500,function(){//pause 0.5s, fade the next image in
    $(this).addClass(‘active’);//and when the fade’s complete add the active class
    });
    });
    }

    $(document).ready(function(){
    $(‘.active’).fadeIn(1500);//fade in when everything’s loaded
    setInterval(function(){cycleImages($(‘#cycler1’))}, 2000);
    setInterval(function(){cycleImages($(‘#cycler2’))}, 3000);
    })

  88. Simon says:

    Depending on how you’re implementing the delay, pass in another parameter to the cycleImages() function, store the delay as a data field against the instance and read it, or just use conditional code to apply the required delay. The first option is the cleanest.

  89. Axel says:

    Hi Simon,
    I have multible instances on one page with different intervalls. Works great. I also added a delay between the pictures FadeIn and FadeOut..
    What I would need now is to have different delays for the different instances. How do I accomplish that ?

    Regards!
    Axel

  90. vincent says:

    Thank you, I get with your code what I was looking for :
    Simple and work great.
    No need to download a heavy library who make that an many other thing that I don’t want.
    I am proud to show you the result in my new web site les-abris-cotiers.com
    Vincent

  91. Elisabeth says:

    I think stopping the script after the last image will solve the problem more easily, as I’m not as good at JS as you are.
    Thanks again for your great help and for your time.
    Happy Xmas and best wishes for the $next year soon $active !
    (I can’t get your script out of my mind !)

  92. Simon says:

    Don’t go to li:first. Fade out the top image each time, which isn’t the first image in the html.

  93. Elisabeth says:

    I already set a different z-index on each li with css, giving a different id to each li. Then the script tells the top one to change its z-index to 1 to go under, and the next to change its z-index to 4 to go up and so on. This way the first cycle is OK, but after it goes back to li:first without setting the z-index of the last element of the list.

  94. Simon says:

    You’re not setting a separate z-index on each image. For 4 images set the bottom one to 1, the next to 1, the next to 3 and the top one to 4. Then fade the top one out and change its z-index from 4 to 1. Then change the other images within indexes 1,2 and 3 to 2, 3 and 4 respectively. Then fade the image with z-index 1 back in. And then repeat.

  95. Elisabeth says:

    I already set a z-index to every image, and everything looks OK until the last image fades out: Then it reappears and stays behind the first when I would like it to go under the pile, as the previous ones did.

  96. Simon says:

    I think you want the top image to fade out and then reappear at the bottom of the pile? In which case I’d set the z-index in the javascript from 1 to n, where n is the number of images. Do this when the page loads, or just set it in your html if that’s feasible. Then fade the nth image out and reset its z-index to 1, increment the z-indexes on all the other images, then fade the old top image with z-index 1 back in.

  97. Elisabeth says:

    The fade effect is fine, but I have no idea of the good syntax to do what you suggest…Here is the page.

  98. Simon says:

    Without seeing your page I’m not sure what you’re trying to do here. If you’re not trying to fade the images, just shuffle them, then remove .fadeOut from your script. If you need to revert to an original z-index you could store the original as a rel or data attribute against the element and then restore this to the z-index when your cycle completes.

  99. Elisabeth says:

    I finaly wrapped everything in a list, to avoid conflicts between the img links and the controls links, and it’s OK.
    But one problem remains. As my version of your fadeshow uses images with different sizes, all visible and superposed one to the other, the superposition order is not the same for the z:index and for the list called by the script, what gives a blinking effect when the next item is moved up the pile by the script.
    Even if I set a z-index for all the list elements, at the end of the list the last image doesn’t go under the others, it stays under the first image and then suddenly the second image fades threw the last one…
    How could it be possible to make the script go back to the z-index order of the begining after the last element of the list ?

  100. Simon says:

    What you describe in your previous post is what I would do. If your page is not working then there’s an error somewhere.

  101. Elisabeth says:

    I think (hope) if you tell me how you would do to put links on the images of your page β€œcrossfade_demo_controls_active”, I will be able to manage whith mine…

  102. Simon says:

    It’s impossible to guess this without seeing your page. Have a look at these pages for some help on debugging jQuery.

  103. Elisabeth says:

    Thanks again Simon!
    addClass (‘play’) in the function pauseSlideshow was missing, and the same for removing ‘play’ and adding ‘pause’ again in the function resumeSlideshow… It works now!
    Then (still with your “crossfade_demo_controls_active” example) I’ve been trying to put links around each img in the html, and adding ‘a’ or ‘.cycler a ‘ before each ‘img’ in the script, but without success… Any idea of what could be missing this time?

  104. Simon says:

    Hard to say for certain without seeing your code, but for this I’d leave the ID on the pause/resume button and assign an additional class to that button via your script to mark the state of the slideshow. Then use that class to set the style. Firebug is good for checking the styles applied when testing your css.

  105. Elisabeth says:

    Thanks a lot for your example crossfade_demo_controls_active !
    I’ve been trying to style the play/pause button too, but ineffectively…
    I changed (css and script) .cycler_controls a#pause_resume to .cycler_controls a.pause_resume and added 2 ids (#pause and #play) to the script in the functions pauseSlideshow and resumeSlideshow and in the incrementation function. But it seams that only the incrementation function works, and the color of the button doesn’t changes when it’s paused.
    Something is certainly missing, probably in the last function, but I can’t find what…

  106. Simon says:

    I’ve never used that approach, so no, sorry, no suggestions.

  107. i’m trying to make this work in a fullscreen environment but after calling webkitRequestFullscreen it doesn’t work. with the absolute positioning nothing is displayed in a fullscreen. Any idea?

  108. Simon says:

    I think this example does what you want.

  109. Elisabeth says:

    Hi Simon,
    How could it be possible to add css (color) to the page number corresponding to the active image ? I’ can’t figure how to set a class into the indexation script…

  110. Simon says:

    I’m not sure why you’re using :nth-of-type(n+2), but have a look at this example.

  111. steve says:

    I found that the absolute positioning on the images interfered with the document flow. I used the following scss to assign relative positioning to the first image, and absolute positioning on the remaining images:

    .image-cycler {
    img {
    position: relative;
    z-index: 1;
    }
    img:nth-of-type(n+2) {
    position: absolute;
    bottom: 0;
    }
    }

  112. Simon says:

    That’s definitely a problem with your css. You’re either missing css or your html doesn’t match your css. Check the examples to make sure you’ve got everything.

  113. daniela says:

    Hi Simon,

    I have a problem and I cannot seem to fix it. For me the images instead of apperaing one on top pf the other they appear on under the other..how could I fix this?

  114. Melissa says:

    Hi Simon,
    I am a total newbie to JQuery and in my class my teacher has us making a “basic” gallery which is coded in a lot more difficult fashion than yours. So much for basic.
    Your codework is a godsend so than you very much. For a long time this evening, I was struggling with getting your codes to work, then I realised that I didn’t have my css file named and linked correctly back to the html. Ah man… the little things haha.

  115. Simon says:

    If it’s always returning false the selectors which assign $active do not match your html.

  116. Willian says:

    Hello,

    this part of the code: $active.next().length > 0 always return false.

    Do you know why?
    Thank you.

  117. Simon says:

    The easiest way would be to give the img an opaque background. Then this will hide any images stacked up underneath it.

  118. Ingo says:

    Hi Simon,
    Thanks for this small code which does nearly what I’m looking for. As one folk wrote some time ago I want to fade transparent PNGs, too. I set the visibility of all img to hidden in the css and the visibility of the active image to visible. This works but looks bad as the next image doesn’t fadeIn. I tried to add this to the script but failed. Do you have a hint? Thanks!

  119. Simon says:

    Erich
    Can’t suggest much without seeing the code, but have a look at this example which uses controls which appear on hover and next/back buttons.

  120. Erich says:

    Simon. Nice work!! I have morphed you examples into a navigation driven set of divs which contain anchors with hrefs and images. Interestingly I tried using setinterval/clear interval but to no avail. I set the a global interval var but clear did nothing. Maybe I was doing something wrong, or maybe setinterval/clearinterval are probelmatic. In any case, I adapted your set timeout and it works. I have to related issues though and am curious to get your thoughts. One, I replaced the page nmber means of navigation with a next and back arrow. The next arrow works just fine but my back arrow fails on the javascript iif equivalent. $active.previous().length > 0 test fails all I was trying to do is the opposite of your next when I reach the beginning and simply set the div:last instead of first. But it never gets that far.
    Two.. my other issue. I have hidden the controls until someone scrolls over the image. Display:none vs. Display:block And it works sort of. I used the .hover event. When I enter the image the pause control shows up. But when I move the mouse over the pause control it blinks on and off almost as if I’d bound mouseover and mouseout event to the div. In fact just to make sure .hover was not acting like mouseover and mouseout, I tried to bind mouseenter and mouseleave events but they never fired. I even just added simple alerts but nothing. So at this point I am stuck with my strangely flickering controls. Any ideas??

  121. Simon says:

    See here for a sliding version. You could replace the timed slideshow with a transition on mouseover, yes, although there’s no mouseover for a touchscreen of course, so you’d need to build in some behaviour to handle that. See this example for a no slideshow, transition on click approach.

  122. dario says:

    Hi Simon, I wonder if I can use a different effect in the transition from an image to another, for example sliding images from left to right, and if it is possible to activate the effect on mouse over, cycling only once. Thanks a lot!

  123. You should take part in a contest for one of the most useful sites on the net.
    I am going to recommend this web site!

  124. Simon says:

    This is easily fixed by applying z-index via your css. If your menu is sitting in #header and all your content is within #content then you need something like:

    #header{position:relative;z-index:2}
    #content{position:relative;z-index:1}
  125. Argh says:

    Ran into an issue: if there is another javascript drop down menu with menus that expand (normally) in the area occupied by the image animation, they are hiding behind the images. What can be done about this?

  126. Simon says:

    Hi Ian
    Yes, I’ve noticed Safari can be a bit jerky at times, especially if you have a lot of images.

  127. Ian says:

    Great thanks Simon, much appreciated.

    I’ve noticed that the script doesn’t run as smoothly in Safari. The fades are a little stuttery. Is this just how it is in Safari? In Firefox & Chrome the fades are really smooth.

    Thanks again – Ian

  128. Simon says:

    Hi Ian

    You should be able to use the code from the variable time demo replacing this:

    setTimeout(function(){cycleImages()},$('img.active').attr('rel'));

    with this:

    if ($('#cycler .active').next().length > 0) setTimeout('cycleImages()',$('img.active').attr('rel'));

    So here the timeout for the next image is only set if there is one – with the result that the images only cycle once.

  129. Ian says:

    hi Simon, I am trying to get this example (below) to stop on the last image. I’ve looked at the script for ‘cycle and stop once’ to compare and there seems to be a few quite significant differences between the 2 scripts. (ie: I’m not completely sure how to)

    http://www.simonbattersby.com/demos/crossfade_demo_variable_times.htm

    Cheers, great little script.

  130. Simon says:

    Easiest is to wrap your images in a div and make the divs a standard size. Then fade the divs in and out as in this example.

  131. dave says:

    What about images of various dimensions? the problem is the top image doesn’t necessarily hide the bottom ones.

    I was attempting to create a mask div; absolute positioned on z-index:3 and then display the active image on z-index:4? Problem is I think the mask would have to be redrawn on each image call in the JS.

    Thoughts?

  132. dario says:

    Yes, now it works perfectly! Thanks again for your patience!

  133. Simon says:

    Take a look at this example (originally for comment 153 above) which I think does almost exactly what you want. The problem you’re having at the moment is that the setTimeout() call within the function is run twice, once for each image, but you only want to run it once. If you don’t want the staggered start, use the same delay argument for both initial setTimeout() calls.

  134. dario says:

    this makes the effect run twice

    function cycleImages(){		  
    	$('.cycler .active').each(function(){
          var $active = $('.cycler .active');
          var $next = ($active.next().length > 0) ? $active.next() : $('.cycler img:first');
    	  
          $next.css('z-index',2);//move the next image up the pile
    	  $active.fadeOut(1500,function(){//fade out the top image
    	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
          $next.css('z-index',3).addClass('active');//make the next image the top one
    	  
    	
    	  if ($('.cycler .active').next().length > 0) setTimeout('cycleImages()',1000);
          });
    	 	 
    		  });
        }
    	
        $(document).ready(function(){
          // run every 1s
          setTimeout('cycleImages()', 2000);
    	 
        })
  135. Simon says:

    If you have a look at the link in my previous response you’ll see some example code for multiple cyclers. You need to use .each() to iterate over all the cyclers.

  136. dario says:

    I can’t find what’s wrong in the code below: this works perfectly only if ‘.cycler’ class is assigned to one element only, not two…

    function cycleImages(){
          var $active = $('.cycler .active');
          var $next = ($active.next().length > 0) ? $active.next() : $('.cycler img:first');
          $next.css('z-index',2);//move the next image up the pile
    	  $active.fadeOut(1500,function(){//fade out the top image
    	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
          $next.css('z-index',3).addClass('active');//make the next image the top one
    	  if ($('.cycler .active').next().length > 0) setTimeout('cycleImages()',1000);
          });
        }
    
        $(document).ready(function(){
          // run every 1s
          setTimeout('cycleImages()', 2000);
        })
  137. Simon says:

    Dario
    Your html has two elements with the same id. An id should be unique in your html and that’s why it’s not working. Use a class instead of an id and amend you jQuery accordingly – like this example.

  138. dario says:

    I’ll give you the example

    your css:

    [deleted]

    your script:

    [deleted]

    my html:

    [deleted]

    It works but not fade in of second image…

    Tanks a lot

  139. dario says:

    hi Simon, great code and a lot of patience in the answers! I’d like to use the code for two images and than stop; I’m applying the code to two different containers but only one will appear depending on device but the crossfade doesn’t work. How can I apply the same code to two different containers?

  140. Simon says:

    Not quite sure how you want this to work, but you could pass a querystring identifying one of the images as part of your URL, and then add some code to the slideshow that reads the querystring and uses this to (say) set that image as the first displayed.

  141. Hi Simon, the code is brilliant and easy thank u so much for publishing it, but i still need help somewhere and i cant seem to find where to get what im looking for. I want to embed something in the url that tells me i stopped at a particular image so that if i send this url the other person would know immediately which picture im referring to. I found out i can do it with anchors but i dont know how to use them, i also have a next and previous button which makes it even harder, i would very much appreciate it if u help me as soon as possible πŸ™‚

  142. Jordan says:

    Gracias Amigo!!

  143. Simon says:

    Sounds like the bottom two images are the gallery, the one on the top just a normal image. Wrap the gallery images in anchor tags, and then fade the anchor tags in and out instead of the images. There’s an example here using divs that should point you in the right direction.

  144. Katarina says:

    Hi all, I have 2 pictures under each other, one on top needs to stay as it is and how it is, bottom one needs to be swapping with third picture over and over again, moreover 2 swapping pics need to have hyperlink so after user clicking on them the document displays, can anyone help please?

  145. Simon says:

    Stuart
    You could do this by including the text and your images in a div, and then just fading the div like this.
    If you want to do something more sophisticated then you can add the text fade to your cycleImages() function.

  146. Stuart says:

    Hey Simon, is there a way of having some text fade/transition with the images?

  147. Mike says:

    Clearly I wasn’t paying attention. Thanks!

  148. Simon says:

    Hi Mike
    The first variation does this.

  149. Mike says:

    How would you make it stop after the last image?

  150. Simon says:

    It looks like you’ve mixed code from two demos. Your code is looking for divs with a class of cycler:

            $('.cycler').each(function(){

    but you have no such divs – your div has an id of cycler. Change the id to class and it should work.

  151. Faisal says:

    Hi Simon i’m sorry if mu question is stupid because it’s my first time i’m using jQuery
    the code did not work with me : this is the HTML file [deleted]

     #cycler{position:relative;}
          #cycler img{position:absolute;z-index:1}
          #cycler img.active{z-index:3}
      
    
    
        
        
        function cycleImages(){
            $('.cycler').each(function(){
    var $active = $(this).find('.active');
    var $next = ($(this).find('.active').next().length > 0) ? $(this).find('.active').next() : $(this).find('img:first');
                $next.css('z-index',2);//move the next image up the pile
                $active.fadeOut(1500,function(){//fade out the top image
                $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
                $next.css('z-index',3).addClass('active');//make the next image the top one
                                              });
                              });
                                }
    
                            $(document).ready(function(){
                             setInterval('cycleImages()', 2000);
                                              })
  152. jenny says:

    thankyou simon!

  153. Simon says:

    To make the first image random you really need to set the active class randomly via your server code – PHP or whatever you’re using. To randomise the next image replace the $next code with something like:

    	  var randomIndex = Math.floor(Math.random() * ($('#cycler img').length-1));//generate a random index from the set of images less one
    	  var $next = $('#cycler img').not('.active').eq(randomIndex);//retrieve the set of images excluding the active one, and select the next image using the random index generated previously
  154. jenny says:

    Hi Simon,
    thankyou so much for your Script! I’m using it at http://www.linnluehn.com.
    How can I manage that the range of the images is completely randomized? Also the start image (.active) and all the following?
    And I’m not able (what you recommend) to add an additional check so that the same image is not selected twice in a row. Can you help me?
    Thanks so much! Jenny

  155. Simon says:

    Here’s how I’d do that:
    -count how many images are in your image container using .length
    – generate a random number between 1 and the number of images using Math.random
    – find the generated image using .eq() – but remember this uses zero based indexes, so the first image is .eq(0) not .eq(1)
    – add the selected div with .append()

    Your code should be considerably shorter than this explanation!

  156. silpa says:

    this page is help me a lot to develop my knowledge in javascript.i just want to try how to select a image from random image collection and that image will store in another div by using javascript.but i was found some error in my programe,what should be the solution

  157. Caroline says:

    sorry this is actually working. Thank you very much for your time

  158. Simon says:

    Your css is wrong. You are setting z-index:1 on #contenu img, and this is taking precedence over where you set z-index:3 for the active image via .petite-image1 img.active etc{} – with the result that the active image does not have z-index:3. Try changing this:

    .petite-image1 img.active, .petite-image2 img.active, .petite-image3 img.active, .petite-image4 img.active, .petite-image5 img.active, .petite-image6 img.active {
        z-index: 3;
    }

    to this:

    #contenu img.active{
        z-index: 3;
    }
  159. Caroline says:

    the first fade out is too brutal…

  160. Simon says:

    I’m not sure I exactly understand your problem. Are you saying that there is too much time before the first fade?

  161. Caroline says:

    no, it doesn’t seem to change anything, I don’t understand where the problem is

  162. Simon says:

    Looks like it might be what I suggested before, For instance, you are calling cycleImages3() (the first cycle) after 4000ms, but then calling subsequent cycles after 1000ms. Is that the problem?

  163. Caroline says:

    Sorry i didn’t wrote the good url the first time. Here you have the good one

  164. Simon says:

    I can’t see a crossfade on your linked page, so I’m not sure exactly what the issue might be. If you are using one of the variants that uses setTimeout rather than setInterval, is it possible that your original setTimeout called from $(document).ready() is set with a different timing that the one called from cycleImages()?

  165. Caroline says:

    Hi, thanks for your script, this is simple and easy to use. I just have one little problem: the first fade out is not working, it’s too speed but the other ones have the speed i indicated in the script. Do you know why i can have this result?

  166. Simon says:

    I’m not quite sure what you’re asking here. If you’re saying there are too many thumbnails to fit nicely then you could add some javascript to make the thumbnails move as the images scroll, so that only a proportion of the thumbnails are visible, and allow the user to scroll the thumbnails. This is quite possible, but not trivial to do.

  167. Kily says:

    Simon thank you for your generosity to share the codes and all. I really interested with your thumbnail controller and manage to make it works with crossfade div as your examples.
    But I’m wondering when the images or div are populated from database which has many records so the thumbnail container will be overflow. How do we handle it?
    Thank again and sorry for my bad english.

  168. Simon says:

    Yes, very possible. I’d start with the slideshow control version, remove the Pause/Resume buttons and hide the controls, and then add a counter to the auto slideshow, and when it’s cycled twice, stop and fade in the controls.

  169. Irena says:

    Hi Simon,
    I wonder if there is possibility to create the following functionality: cycle through all images twice and than auto cycling stops and manual starts: the controls become visible and I can navigate through the slides manually.

  170. David says:

    Thank you very much! First one who did the most clean version!

  171. Simon says:

    Have a look at this example for using thumbnails with no automatic transition, or this example for slideshow controls. View the source to see how click events are managed.

  172. sira says:

    hy,

    helped me a lot with that!

    but how do i add a click function. for example when i have some image thumbnails under the big image fade.

  173. rig says:

    that was the problem, thank you

  174. Simon says:

    Your page does generate a console error: ‘ReferenceError: cycleImages is not defined’.
    Move the function definition outside the $(document).ready() call.

  175. rig says:

    http://www.rigadonne.ro/despre.html. The picture to the left is the gallery.

  176. Simon says:

    I can’t help without a link to your page.

  177. rig says:

    jquery is loaded, no erros, nothing, told you – other jquery functions work…

  178. Simon says:

    Do you have jQuery loaded on your page? Do you get any console errors? Have a look at this page for help with debugging.

  179. rig says:

    Hi! Maybe it’s a silly question but, i put all the code in the js file and when i open the webpage, nothing happens. Other javascript works in my document but the parte with the crossfade gallery doesn’t.. what did i do wrong ? the only difference is that a have #l_g instead of cycler.

  180. Peter says:

    Thank you Simon! Using CSS to hide the pause/resume area worked like a charm — you rock! Thanks again!

  181. Simon says:

    Peter

    If you don’t add the pause/resume then you won’t be able to resume the slideshow after clicking on one of the page ‘dots’, so I’m not sure how you envisage your slideshow working.
    If you just don’t want the ‘Pause’, just the ‘Resume’ then you could just hide the Pause control with css:

    #pause_resume.active{display:none}

  182. Peter says:

    Simon, this has helped me a ton! I do have one question though. I’ve used navigation dots for the banner, but am wondering how I would remove only the “pause” & “resume” buttons without removing the slideshow timing & the pause functionality when you click on an one of the navigation dots.

    Below is the JS of yours that I’m using:

    function cycleImages(containerBanner){
          var $active = containerBanner.find('li.active');
          var $next = ($active.next('li').length > 0) ? $active.next('li') : containerBanner.find('li:first');
          $next.css('z-index',2);//move the next image up the pile
          $active.fadeOut(1500,function(){//fade out the top image
    	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
    	  containerBanner.find('.cycler_controls a.active').removeClass('active');
              $next.css('z-index',3).addClass('active');//make the next image the top one
    		  containerBanner.find('.cycler_controls a').eq($next.index()+1).addClass('active');
          });
    	  var timer = setTimeout(function(){cycleImages(containerBanner)},5000);
    	  containerBanner.data('timer',timer);
    }
    
    function pauseSlideshow(containerBanner){
    	clearInterval(containerBanner.data('timer'));
    	containerBanner.find('li.active').stop(true,true);
    	containerBanner.find('#pause_resume').html('Resume').toggleClass('active');
    }
    
    function resumeSlideshow(containerBanner){
    	var timer = setTimeout(function(){cycleImages(containerBanner)}, 500);
    	containerBanner.data('timer',timer);
    	containerBanner.find('#pause_resume').html('Pause').toggleClass('active');
    }
    
    $(document).ready(function(){
    	
    	var i = 1;
    	$('#cycler').each(function(){
    		var containerBanner = $(this);
    		containerBanner.append('Pause');
    		for (var j=0;j<=containerBanner.find('li').length-1;j++){
    			containerBanner.find('.cycler_controls').append(''+(j+1)+'');
    		}
    		containerBanner.append('').addClass('cycler'+i);
    		containerBanner.find('.cycler_controls a').eq(containerBanner.find('li.active').index()+1).addClass('active');
    		var timer = setTimeout(function(){cycleImages(containerBanner)}, 5000);
    		containerBanner.data('timer',timer);
    		i++;
    	});
    	  
    	$('.cycler_controls a.page').click(function(){
    		var containerBanner = $(this).parents('#cycler');
    		pauseSlideshow(containerBanner);
    		containerBanner.find('li').eq($(this).attr('rel')).css('z-index',4).addClass('clicked');//set the clicked image to the top
    		containerBanner.find('li.active').not('.clicked').removeClass('active').css('z-index',1);//if the active image is not the clicked image, remove the active class 
    		containerBanner.find('.clicked').addClass('active').removeClass('clicked');//set the active class on the clicked image ready to resume
    		containerBanner.find('.cycler_controls a.active').removeClass('active');//remove the active class from the matching control
    		containerBanner.find('.cycler_controls a').eq(containerBanner.find('li.active').index()+1).addClass('active');//set the new control active
    		return false;
    	});
    	
    	$('.cycler_controls a#pause_resume').click(function(){
    		var containerBanner = $(this).parents('#cycler');
    		if($(this).hasClass('active')){
    			pauseSlideshow(containerBanner);
    		} else {
    			resumeSlideshow(containerBanner);
    		}
    		return false;
    	});
    	  	
    })
  183. heinz says:

    Thank you very much, its amazing. simple and good excellent

  184. Roy says:

    Aha! You never know what CSS these template authors are hiding. Somewhere in the pile there must’ve been a text-align:center. I’ve aligned left and no more shifting image. Sorry to bother you. Keep up the good work!

  185. Roy says:

    Simon. Thank you for the code and thank you for responding consistently to a 190+ comment thread. Wow, dude. Wow.

    I’ve put this into a Yahoo Store and it works nicely but before my page fully loads the active image in the script is oddly positioned way off to the right. Then the page finishes loading and the image shifts/snaps into its proper place. I’m still tinkering but I thought I’d ask if you’ve any off-the-top-of-your-head solution for this. Thanks again.

  186. Jimy Mason says:

    Thanks, that worked a charm. Keep up the good work.

  187. Simon says:

    It’s easy enough. Adapt the multiple cyclers example to cycle divs instead of images – like this example, then just put your link in the div.

  188. Jimy Mason says:

    Has anyone here managed to modify the multiple cyclers javascript to accept links?

  189. Jimy Mason says:

    I found the problem thanks:

    “media=”print”

  190. Simon says:

    OK, then either your html or css is not right then. If you’re using the css given on this page then the html is wrong, resulting in the css not having any effect because the id in the css isn’t in the html. If the javascript works OK, however, sounds like it might just be your css.

  191. Jimy Mason says:

    Simply that the images are lining up next to each other rather than on top of each other and floating them doesnΒ΄t seem to change that

  192. Simon says:

    WordPress has eaten all the code you pasted, I’m afraid.
    If it does fade, what’s the problem you’re seeing?

  193. Jimy Mason says:

    The fading occurs, so it must not be a javascript or jquery problem, the html is as follows:

    Right now i am just preparing this to see how it would function on my non-live website.

  194. Simon says:

    No, that css will set all the images to absolute positioning, assuming you have the images within a div with id of cycler. Have you set the first image with the active class?
    What is happening, is the page displaying correctly but not fading? If so have you loaded jQuery and the javascript properly? If you’re still struggling post a link to your page.

  195. Jimy Mason says:

    This is all i have for the CSS so far, and i still canΒ΄t get it going:

    body {
    font-family: Arial, Helvetica, sans-serif;
    color: #666666;
    margin: 0;
    padding: 0;
    background-color: #eeeeee;
    }

    #cycler {position:relative;}
    #cycler img{position:absolute;z-index:1;background-color:white}
    #cycler img.active{z-index:3}

    .container {

    width: 450px;
    float: left;
    margin-left: 50px;
    display: inline;
    margin-bottom: 40px;
    }

    Am is supposed to have another css id for the images that arenΒ΄t active, and then set that to have absolute positioning?

  196. Simon says:

    Have a look here and here – you should be able to combine the code to suit what you want. It’s just a case of replacing the fade transition here with an animation to move the image to the left.

  197. Gideon says:

    How would I make it slide away to the left instead?

  198. Gideon says:

    Thanks, got it working, well made man πŸ™‚

  199. Simon says:

    You can copy the code from any of the examples given – view source to see how it’s done. If you’re still not having any luck, have a look at this debugging guide.

  200. Gideon says:

    Can someone give me a download? I cant get it to work.

  201. Simon says:

    Jimy
    You need to use the css I’ve given above to position the images using position:absolute so they stack up on top of each other.

  202. Jimy Mason says:

    Hi Simon,

    Just a quick question, how do you lay the images over eachother? I had a look through the code but i couldnΒ΄t seem to find the cause.

    Regards,
    Jimy

  203. Simon says:

    Hi Rafid

    Never seen that happen. Just tested and I don’t see an issue with 12 images fading in and out.
    If you want to have a random image then you’d just need to edit the code that finds the next image. Have a try using this instead:

    var $next = $('#cycler img').eq(Math.floor((Math.random()*$('#cycler img').length)));

    You might want to add an additional check so that the same image is not selected twice in a row.

  204. Rafid says:

    Actually I tried playing around with the number of photos and it seems that it works perfectly fine for up to 10 photos, once I add in the 11th I get this problem. I only had 11 anyway so I’ll settle with removing one.

    On another note, how can I make the selection of the next photo to be random ? rather than always fading to the next photo sequentially from 1 to 10, I’d like it to be randomly choosing the next photo from the 10 photos all the time

    Thanks
    Rafid

  205. Simon says:

    Hi Rafid

    That sounds like the jQuery is not correctly finding the first image to fade in – this can be caused if your html isn’t quite right. If you can’t find the issue, post a link to your page.

  206. Rafid says:

    Hi Simon,

    Thanks for the script, while looking at the dates of all the comments I thought it was great to see that you’ve been active on the comments and helping out every single person for 2 years now.

    I used your initial script, but I am having a slight issue where when the last image shows up (it fades into it fine), all of a sudden it instantly changes to the 2nd last image (without a fade) and then back to the first image (also without a fade). Not sure if anyone else is having this problem but, is there a way to make sure that when it reaches the last image it fades back into the first image (no instant switch) ?

    Thanks
    Rafid

  207. Simon says:

    Hi Asana

    Glad we got there in the end! Just a credit in the js comments would be fine.

  208. Asana says:

    You are the BEST! Thanks so much for your help….it works perfectly. I guess you can tell this isn’t my area of expertise. I would like to credit you for the script in the code. Is there any particular way you want me to list the credit?
    THANK YOU! Have a drink on me and enjoy your weekend.
    Asana

  209. Simon says:

    No, I think you still haven’t got the javascript right. Your cycleImages() function has:

    var $active = $('.cycler').find('.active');

    which should be

    var $active = $(this).find('.active');

    Here’s a corrected version of your code.

  210. Asana says:

    Still glitching out. Could it be the hosting server?

  211. Simon says:

    Hi Asana

    Thanks for the donation! Your example works OK up to the point of restarting through the images, suggesting the issue is with the code that picks the next image. Your code has:

    		  var $next = ($active.next().length > 0) ? $active.next() : $('.cycler').find('.cycler img:first');

    Try replacing this with (as my example):

    var $next = ($active.next().length > 0) ? $active.next() : $(this).find('img:first');
  212. Asana says:

    Hi Simon! Thanks for getting back to me. I copied the code just as you have it on this page: http://www.simonbattersby.com/demos/crossfade_demo_multi.htm, however mine is still glitching out on me once it gets to the last group of images so I am not sure what I am doing wrong. I did notice that in some examples you gave the div a cycler id while in others you gave the div a cycler class. I tried it both ways but with the “cycler id” it only cycles thru the first image and then stops. Your example is so smooth and seamless but mine is glitchy in every browser I have tested.

    Here’s my code – anything that looks like it could be my problem?

    function cycleImages(){
    $(‘.cycler’).each(function(){
    var $active = $(‘.cycler’).find(‘.active’);
    var $next = ($active.next().length > 0) ? $active.next() : $(‘.cycler’).find(‘.cycler img:first’);
    $next.css(‘z-index’,2);//move the next image up the pile
    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).show().removeClass(‘active’);//reset the z-index and unhide the image
    $next.css(‘z-index’,3).addClass(‘active’);//make the next image the top one
    });
    });
    }

    $(document).ready(function(){
    // run every 3s
    setInterval(‘cycleImages()’, 3000);
    })

    Thanks again. I would be happy to give you credit for the script if I can get this working!
    Asana

  213. Simon says:

    Asana

    What’s happening at the moment is that at the end of the first cycle only the first cycler is tripping back to the first image. If you look at the javascript on my example it’s different from yours because I’m doing this:

    function cycleImages(){
    	  $('.cycler').each(function(){
                   //stuff to fade out the images 
    	  });
        }

    Wrapping the fade code in the .each function is what you’re missing.

  214. Asana says:

    Hi Simon…I am trying to implement your jQuery Crossfade – multiple cyclers with common periodicity but I am missing something in my javascript. I was able to make it work here: http://www.compassidaho.org/homeimages-test.html but the last 2 divs end up getting stuck at the last image so I used the code you indicated to Kate on November 9, 2011 but it won’t work. I imagine somewhere I have replaced the (this) with incorrect information?

    I also compared to the JS you used on this page: http://www.simonbattersby.com/demos/crossfade_demo_multi.htm but I cannot make that work either.

    Any suggestions would be greatly appreciated!

    Asana

  215. Mike says:

    Thanks Simon, Worked a treat

  216. Simon says:

    Peter
    Use the example for cycling divs, but just change the js so that it only looks for divs that are immediate children of #cycler, like this:

    var $next = ($active.next().length > 0) ? $active.next() : $('#cycler > div:first');
  217. Peter says:

    Hello Simon,
    It is a very nice fader that you have made. It works perfect, but I have one question: how can I put an image in de left corner that should stay there, like the div text on de right side. I ‘ve put the img in the div “cycler” on the html page. It looks oke. But, at the end of the cycle, the image messes up the order of the last two images and then fades. Can you tell me how to do that?

  218. Simon says:

    Yasmin

    You can adapt the code in this example for your ‘pause on hover’ option.
    Adding the rating tab on :hover should be pretty straightforward, and you can probably do this with css only – you’d need to wrap your images in divs and adapt this example to do that – hide the text in css, and just show it when the div is hovered.

  219. Yasmin says:

    Hi Simon! Great code, really helpful! πŸ™‚

    Just a quick enquiry, I would like the images to pause when the mouse is hovered over it. With previous sliders, I’ve used pauseOnHover: true, – However, I cannot see where this would fit within the code for your slider.

    I’d also like a kind of ratings tab to appear over the image when the mouse is hovered, I realise this is a lot to ask all at once, apologies!

    Many thanks πŸ™‚

  220. Gord says:

    Ah yeah I see now… thanks Simon
    Very nice of you to do that I appreciate the example.

  221. Simon says:

    You’re not setting up the cycler controls correctly, and the cycleImages function needs to ignore the cycler controls div in the cycle, otherwise you’ll end up fading the controls.
    Have a look here.

  222. Gord says:

    Simon, Re #53 I tried this but it didn’t work.
    What am I missing?

    [code removed]

  223. Victor says:

    Great Simon! Thanks very much!

  224. Simon says:

    Hi Victor

    Have a look at this example, which has multiple cyclers with different periodicity, stopping after one cycle. The page you link to, however, appears to have multiple cyclers with a common periodicity but staggered starts. If this is actually what you want, you can set a standard periodicity but amend the initial call – like this.

  225. Victor says:

    Hi Simon, your script is great!! Can you plse help with this: I need multiple cyclers (with different periodicity) to stop after 1 cycle and end, showing the last image. Can you show me how that’s done?
    Victror

  226. Simon says:

    Use the crossfadeImages() script from this, and use it with the control click events on the other script. It’s not quite just a simple cut and paste, you’ll need to edit the code as well.

  227. Michael says:

    Hi Simon,
    script works great, thanks a lot. Still I have the same problem, which has been discussed in posts 83 – 86, but I don’t get the code from the two examples combined the right way. Could you give me a hint, how that is done?
    Michael

  228. Matt says:

    Ahhhh thanks and that worked perfectly!

  229. Simon says:

    You haven’t set a width and height for the div – it needs to have a standard width and height otherwise, as now, larger images will be visible behind smaller images. You can position the images within the div as required.

  230. Matt says:

    Hmmm Looks like it is still doing it or I messed something up. Here is the link to the page. It is that “Rotating Image” in the middle of the page. This site was made long ago too so forgive the tables heh.

    http://www.menomoneefallsdowntown.com/index-new.iml#

  231. Matt says:

    Thanks Simon I will do that now and thank you so much for the quick reply. If I run into an issue I will let you know but I should be good. Thanks again!

  232. Simon says:

    Matt

    The way to do this would be to place the images in a div big enough to contain the largest image, give the div a background colour to suit your design, and then fade the divs instead of the images, like in this example.

  233. Matt says:

    Simon perfect script and a lot less code then others I have found for just a basic image fader. One issue though. What if the images are different sizes in height or width? When I have a small image and it fades to it, it shows the bigger images behind it still. I am hoping when it fades to the smaller ones that all other images stay hidden till their turn in the rotation.

    Thanks!

  234. Len says:

    Thank you Simon. It works like a charm, much appreciated. I’m going to try it in a responsive website;thanks very much again!

  235. Simon says:

    Len

    If you add a bit of css to hide the text, then you can add a fadeIn to the callback on the crossfade:

    function cycleImages(){
          var $active = $('#cycler .active');
          var $next = ($active.next().length > 0) ? $active.next() : $('#cycler div:first');
          $next.css('z-index',2);//move the next div up the pile
          $active.fadeOut(1500,function(){//fade out the top div
              $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
              $active.find('p').hide();//hide the text
              $next.css('z-index',3).addClass('active');//make the next image the top one
              $next.find('p').fadeIn('slow');//fade in the text
          });
        }

    Haven’t tested this, but it should do something like what you need.

  236. Len says:

    Hi Simon, Thanks so much, I really appreciate your time, the text has to fade in after the image is already loaded, but I’ll work with this, thanks so much again.

  237. Simon says:

    There should be no need to create the text as a .png. Wrap both the image and the associated text in a div, and fade the divs in and out rather than the images, as in this example.

  238. Len says:

    I am a newbie and I’ve tried your multiple crossfade, thank you so much. I’m sorry if this doesn’t make any sense, but I have to create text that appears after each image is loaded and fades out with the image, with a different sentence appearing on the second image and so on. I’ve tried saving the text as a png’s and bringing it in a separate container, but the whole container shows up as white when placed on top of container containing the images.

  239. DJO says:

    That’s it! Thank you… You were saying all along “give ’em different id’s” and I was thinking… I don’t know what πŸ™‚ Thank you man!

  240. Simon says:

    Your css doesn’t mean much without the html to go with it, but if you’re using absolute positioning it should be very straightforward. Here’s a tweaked version of the multiple crossfade with ids assigned to both containers, then css used to set absolute positions. Vary top and right settings as required.

  241. DJO says:

    In the end, i got them both to work, and the first one is positioned properly. Second now works too, but its aligned poorly. (i actually tried to get the L shape position of cyclers). So no _ is alined OK but | isn’t :). Adding second class to the second cycler just isn’t working – as I said i don’t know what to do unfortunately.
    i made:
    .container {
    height: 90px;
    width: 960px;
    position:absolute;
    }
    .container2 {
    height: 600px;
    width: 300px;
    position: absolute;
    top: 300px;

    }
    .cycler{position:relative;}
    .cycler img{
    position:absolute;
    z-index:1;
    }
    .cycler img.active{z-index:3}

    #cycler{position:absolute;}
    #cycler img{
    position:absolute;
    z-index:1;
    left: 12px;
    top: 0px;
    }
    #cycler img.active{z-index:3}

    ……
    I also added the:
    #apDiv1 {
    position:absolute;
    width:300px;
    height:600px;
    z-index:1;
    }
    to try to align the layer. No luck. The _ is aligned fine. The | isn’t *(they form “L” as I said)
    ….
    I’m just stuck πŸ™ Sorry. Any ideas?

  242. Simon says:

    If it was working OK at one point, then get back to that. Then add ids to each of the cyclers, and add css to position those elements as required.

  243. DJO says:

    Yes. I put 2 cyclers. one horizontal middle page one vertical to the right of the page, and I need them positioned properly on the page.
    I tried to position the layers first (named them container1 and container2) and made css for it, and then I put the cyclers inside – but couldn’t get them to work. I really don’t know what to do…

  244. Simon says:

    I’m guessing you’re using the multiple cyclers on a page example where each cycler is referenced by the jQuery using a common class of cycler, and then applying css to .cycler.
    The use of a common class simplifies the jQuery somewhat, but you can add an id (or another class) to your cyclers if you need to position them individually – just leave the class of cycler in as well.

  245. DJO says:

    Hi Simon,
    First THANK you for this fade. I tried to put 2 of those on my page and I do get them to run, however I can’t get one of them into proper position – or rather when I move it left: 10px; top: -90px; the other module moves as well πŸ™
    My question is why it isn’t possible to name one cycler1 and the other cycler2 so we get more space for proper positioning of the module?
    *this comes handy especially for <!– [if IE]… when it's needed to move things pixel or two so it fits.
    can you please write a proper thing for this (i guess it's just a slight moderation of your post to Kate at the top of the page – but i don't know how to do it. Thank you in advance

  246. Simon says:

    If you want each image to have a separate link, then you can wrap the images in a tags, and then amend your script so it fades the a tags containing the images rather than the images themselves. Have a look at this example which fades divs which uses a very similar approach. This is the preferable approach, but another option would be to just attach click events to the images with javascript, and use window.location.

  247. Hello

    Simon
    I’m not good at english
    please understand

    your work is great.
    I made some pages above the link

    there are 3images I use,

    I tried to add link to each images

    intro001
    intro002
    intro003

    but I have on idea about it.

    please check my pages

    regards

    Chogn hyo, Rhee
    from seoul, KOREA

  248. Dave says:

    thanks this is excellent!

  249. Simon says:

    Robert

    Your code is working in a different way in that it’s cycling the background image of the element. This cannot be faded. If you want to fade your images then you’d need to amend your html such that image is rendered as an img element on the page, and then fade or crossfade that.

    Vivek

    Do you mean crossfade three images at a time? If so then put each of your sets of three images in a div, and cycle the divs like this.

    Chris

    Because I think they’re interesting.

  250. Chris says:

    Great tutorial, but why images of flies?? πŸ˜€

  251. Vivek says:

    Hi,
    Awesome work.

    I was wondering how I would make the crossfader jump between many sets of images? So if I had 4 sets of 3 images each, I’d want to show the next set of images to be cycled through when an arrow key is pressed? I’ve been playing around with this but its not as robust as I’d like.

    How could I do this?

  252. Robert says:

    Hello,
    Could you show me how the same effect can be achieved with the existing code I’m using below? I am not cycling contained images but i am cycling the background image of a div but really need the change to occur as a crossfade or even just a fadein instead of the POP in.

    var imageIndex = 0;
    var imagesArray = new Array();

    //Set Images
    imagesArray[0] = “images/self-whitewater.png”;
    imagesArray[1] = “images/fishing.png”;
    imagesArray[2] = “images/solo-kayaking.png”;

    function cb(){

    $(“#main-blocki”).css(“background”,”url(‘”+ imagesArray[imageIndex] +”‘)”);

    imageIndex++;
    if (imageIndex > 2)
    imageIndex = 0;

    }

    $(document).ready(function () {

    setInterval(cb,5000);

    });

  253. Simon says:

    Ken

    You should be able to do this quite simply by adapting the code for the slideshow with controls variant.
    You can reuse the pauseSlideshow() and resumeSlideshow() functions within this example, and attach them to mouseenter and mouseleave events instead of click events.

  254. Ken says:

    Hi,

    I’m running the script to crossfade DIV’s. I have DIV tags nested into the “cycler” DIV and used some extra classes to make it work. So far so good (thanks for the base code !).

    As an extra, I’d like to pauze the automatic crossfade to the next image when hovering over the DIV element, so visitors have the time to read the content. I tried but didn’t get that part to work…

    Thanks in advance for brilliant ideas πŸ™‚
    Ken

  255. Don says:

    Perfect! Thank you!

  256. Simon says:

    Yes. To do this alter your css slightly:

    #cycler{position:relative;}
    #cycler img{position:absolute;z-index:1;display:none}
    #cycler img.active{z-index:3;display:block}

    This will hide everything but the top (.active) image, so only the top image will be seen loading. Then amend your javascript so it runs on $(window).load instead of $(document).ready:

    $(window).load(function(){
      $('#cycler img').show();
      // run every 7s
      setInterval('cycleImages()', 7000);
    });

    The window.load event will not fire until all the page elements have loaded, unhide the remainder of the images and then start the cycler.

  257. Don says:

    Thanks Simon. This is great. Is there a way to only show the “active” (first) image while the other images are loading in the background? I’ve noticed that in some browsers all the images can be seen loading before the animation starts.

  258. Glen Haynes says:

    Thanks Simon, that works perfectly.

  259. Simon says:

    Shadna

    Yes, what you’d need to do is just replace the numbers on the ‘controls’ variant with copies of the images, like this.

  260. Shadna says:

    Hi! This is a really simple solution and works great for my project. One thing…

    On the original site we had a banner area (now the slideshow) that had thumbnail images below that would load the appropriate slide. Anyway to do that with this? Let me know! Thanks!

    Shadna

    PS – site is utahwomenswalk.com

  261. Paul Coulson says:

    Thanks – extremely useful.

  262. Simon says:

    Hafi

    There’s no way of telling what the problem is without seeing your page – it sounds like it’s an issue with your css.

    Diego

    Again, no way of suggesting what the conflict might be without seeing your page. jQuery is just javascript, by the way. Check you’re just calling jQuery once, and have a look at your console to see if any errors are generated.

  263. Diego says:

    Hi, I’m using your jquery with other javascripts and when I call the jquery, the javascript (a gallery of images that pop ups) doesn’t work. Do you have an idea how to solve the problem?
    If I take out the line () the javascript works. Thanks for your help.

  264. hafi says:

    hi simon, thanks for the code, it’s simple and sweet.

    i have a problem when i try to implement this slideshow on my almost-ready-site, the #cycle div is making some of my content to go underneath it, because of the “position:relative/absolute” issue.

    i’m not sure what can i do to fix this?
    your help would be appreciated, thanks again.

    (sorry for my poor english, i’m not a native speaker)

  265. Todd says:

    To one who isn’t a programmer (me), it seems like a really creative appropriation. Thank you again for your time, Simon, as I learned a lot from your crossfade examples.

  266. Simon says:

    I’m just using it here as a convenient attribute to store the ordinal number (1st, 2nd etc) of the image to be shown when the link is clicked – used as the index for the .eq() function here:

    container.find('img').eq($(this).attr('rel'))....
  267. Todd says:

    Thank you for walking me through me through this, Simon. I thought that the “rel” attribute was the key, but I didn’t know what values to assign to it. It’s so innocuous in html, that I can’t imagine using it in a script.

  268. Simon says:

    Assuming you’re never going to change the two items for the fade, then I’d replace this:

    	for (var j=0;j<=$('#cycler').find('div').not('.cycler_controls').length-1;j++){
    		$('.cycler_controls').append('<a class="page" href="#" rel="'+j+'">'+(j+1)+'</a>');
    	}

    with this:

    $('.cycler_controls').append('<a class="page" href="#" rel="0">Photo</a>');
    $('.cycler_controls').append('<a class="page" href="#" rel="1">Map</a>');

    Doing it like this will mean that in the event of the user having js disabled, then the controls are not shown, which is what you want.

  269. Todd says:

    Hi Simon,
    In comment #103, you kindly showed me how to disable cycler_code. I must admit that I’m unsure how to hard code “Photo” | “Map” links in order to click back and forth between a photo and a google map. Thank you again for your wonderful blog.

  270. Simon says:

    Yes. The code as posted on this page cycles image elements only. Position your div absolutely and use z-index to make sure it’s on top. This similar example may be helpful.

  271. Jay says:

    Is it possible to place a div ‘ontop’ with in the #cycler div without the ‘ontop’ div being cycled or messing up the cycle of the images?

  272. Simon says:

    You’re welcome. Thanks for the nice comment!

  273. Todd says:

    Wow, Simon,
    How do you manage to help so many people here? You respond so quickly and freely, and it is truly generous of you!
    Thank you so much for your time and for your expertise.

  274. Simon says:

    Hi Todd

    You’re getting that link because your code is seeing the .cycler_controls div as well. You can amend the loop statement to exclude this:

    for (var j=0;j<=$('#cycler').find('div').not('.cycler_controls').length-1;j++){

    However, if you’re always going to have two images then you can remove that loop entirely and just hard code your links in – I wrote the code to cope with however many images are present, but you may not need that functionality.

  275. Todd says:

    Hi Simon,
    Thank you so much for your help. With an iframe within a div, it seems to behave just the same as if it were an image. I have a sample here at http://userpages.bright.net/~toddw/crossfade.html

    I’m getting one too many links (number 3), but I would rather have just two static links, i.e., “Photo | Map”

  276. Simon says:

    Hi Todd

    Never tried that, but you can certainly fade divs in and out in the same manner – so you could wrap both your images and your iframe in divs and fade those.
    Have a look at this example – same idea with some minor tweaks to the jQuery.

  277. Todd says:

    Hi Simon,
    Your crossfade may be “simple”, but it’s buttery smooth.

    I want to crossfade between a static image and an iframe (google map), but the iframe isn’t an ‘img”. Is there a way to enable the script to recognize the iframe as an image source?

  278. Simon says:

    Do you have your html set up correctly? Just guessing without seeing your page.

  279. Jay says:

    I didn’t, my bad tiredness got the better of me, I now have it working but after the first cycle it cycles to white and stays white, any ideas?

  280. Simon says:

    Do you have jQuery loaded on your page? Have a look at the demo page to make sure you have evrything loaded.

  281. Jay says:

    I have this code set my page, it doesn’t do anything in the only two browser I have tested. (IE, Chrome)

    function cycleImages(){
    var $active = $(‘#cycler .active’);
    var $next = ($active.next().length > 0) ? $active.next() : $(‘#cycler img:first’);
    $next.css(‘z-index’,2);//move the next image up the pile
    $active.fadeOut(1500,function(){//fade out the top image
    $active.css(‘z-index’,1).show().removeClass(‘active’);//reset the z-index and unhide the image
    $next.css(‘z-index’,3).addClass(‘active’);//make the next image the top one
    });
    }

    $(document).ready(function(){
    // run every 7s
    setInterval(‘cycleImages()’, 1000);
    })

  282. Simon says:

    If twitter needs 1.6.1 remove the other one and give that a go.

  283. Dom says:

    I’m using
    ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
    for this fader (not slider, ignore that) and

    ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js”
    for twitter. The code comes from here – queness.com/post/8567/create-a-dead-simple-twitter-feed-with-jquery

    I am fairly useless at these things and can only copy and paste rather than code from scratch i’m afraid hence don’t understand what the code is doing…

  284. Simon says:

    googleapis.com is the content delivery server, not an application. You’re probably loading jQuery from it. If you’re loading jQuery twice, then that is likely to cause problems, usually manifesting as nothing working however, which isn’t what you were describing earlier.

    Assuming you are tallking about jQuery versions, I’ve no idea about what twitter needs. The crossfade will work with jQuery 1.4.2 and later, and probably earlier as well.

    Not sure what slider doesn’t work….but if you’re using jQuery UI as well for something you need to make sure the jQuery UI version is compatible with jQuery. Certainly jQuery 1.9 changed the interaction between them.

  285. Dom says:

    Basically I’m hosting using Dropbox (to show team at the end of everyday) and working locally where the fade and twitter work fine on chrome, safari and moz. When I host to dropbox it works fine on safari and moz but with Chrome the twitter feed drops out and slider works. I only know these googleapis to copy and paste and have a 1.9.1 for this and a 1.6.1 for twitter. I don’t know if this makes sense to you. Is there a googleapis that is up to date that will cover all these libraries?

  286. Simon says:

    Your posted code has been chewed by WordPress. I can’t think Twitter is the issue. Does the problem resolve if you remove the Twitter feed?

  287. Dom says:

    I’m also using a Twitter feed (this is my head setup, is there conflict between the two googleapis?)

  288. Simon says:

    This page works fine for me in Chrome, as do the demos. If you are using a lot of images, or resized images, I’ve seen Chrome occasionally behave unexpectedly.

  289. Dom says:

    The fader doesn’t appear to work on Chrome, it’s fine on safari and firefox.

  290. k4p says:

    thx!

  291. Simon says:

    Yes, you’d need to combine these two examples.

  292. Jasper says:

    Thanks, that works great! However, I just noticed something.. When pressing the numbers, you don’t get that nice fading animation. Is it possible to implement that? That would definitely make my day ^-^

  293. Simon says:

    Yes, needs some slightly convoluted selectors to do so. Have a look at this demo.
    Just knocked it up quickly so let me know if it works or not.

  294. Jasper says:

    Hi!

    I’m very new to jQuery and I’m wondering if it would be possible to indicate on which “slide” you’re on in the slideshow controls.. If we take a look at this page: http://www.simonbattersby.com/demos/crossfade_demo_controls.htm – is it possible making the number “2” bold if we’re on slide 2 and number “3” bold if we’re on slide 3?

  295. Marc says:

    Thanks Simon, I just worked that out before I checked back here! It’s working perfectly now πŸ™‚

  296. Simon says:

    $active is a variable, you don’t need to change that. That line should be:

    var $active = jQuery(β€˜#slideshow .active’);
  297. Marc says:

    $.backstretch is for this: http://srobbin.com/jquery-plugins/backstretch/ (Very useful!). Removing it from the code doesn’t help.

    I’ve tried wrapping it in ‘(function ($) { })(jQuery);’ That doesn’t seem to help. I’ll try changing all ‘$’ to ‘jQuery’, but how do I change these:

    var $active = $(‘#slideshow .active’);? I know it shouldn’t be jQueryactive … or should it??

  298. Simon says:

    Try replacing $ with jQuery in the cycleImages() function – WordPress uses .noConflict() as a default.
    I don’t know what .backstretch does – does removing it solve the problem?

  299. Marc says:

    I’ve changed something, and now get this instead…

    Type Issue:
    ‘undefined’ is not a function (evaluating ‘$(‘#slideshow .active’))

    This is my code at the moment…. http://pastebin.com/Hf9WfqZ2

    I need to include $.backstretch for another script.. could this be what is throwing it off??

  300. Simon says:

    Something wrong with your jQuery somewhere then. Have you included the code to define the function cycleImages() correctly?

  301. Marc says:

    This is simple, just what i’m looking for, but for some reason I cant get this working in a WordPress environment.

    After the delay I get an error in the console: Can’t find variable: cycleImages

    Any ideas??

  302. Simon says:

    Well, the obvious remedy is not to click randomly and fast – why would anyone do this?
    It’s fairly difficult to recreate, but if it’s really an issue you could reduce the fadeOut time so there’s less chance of another click before the fade completes.
    Another option would be to disable clicks until the transition completes.
    .stop() doesn’t help here I think as implementing that will also lead to jerky behaviour in the circumstance you describe.

  303. herperderper says:

    Hi, your crossfade_demo_no_slideshow
    acts weirdly if I click randomly and fast on numbers from 1234

    Is there any remedy to this?

  304. Simon says:

    You’ll need to edit this section of code:

    	for (var j=0;j<=$('#cycler').find('img').length-1;j++){
    		$('.cycler_controls').append('<a class="page" href="#" rel="'+j+'">'+(j+1)+'</a>');
    	}

    It’d probably be easier to run this using .each() for the images, append a link as above, wrapped around the image. You’ll need some css as well to reduce the size of the images.

  305. Flash says:

    Where do the image links go in the javascript?

  306. Simon says:

    Yes. You’d just need to add the thumbnails when the image links are created.

  307. Flash says:

    Hi, I am using the demo for the jQuery crossfade with no slideshow, and instead of controlling the images by the numbers I want to use small thumbnail images. Can this be done?

  308. Simon says:

    Bob

    The images are all just stacked on top of each other at the moment, which is why you can see the images ‘at the back’ if they’re not all the same size. Wrap your images in divs, apply some appropriate css to position the images within the divs and give the divs a solid background colour to obscure the other images. Then fade the divs instead of the images, as in this example.

  309. Bob says:

    You’ve got a great script, thanks for this … I have one problem: some of my images are smaller than the others, when this occurs then I see all the others in the pile behind it … how can this be solved?

  310. Simon says:

    Sascha

    I’ve added another variation that does this.

  311. Sascha says:

    Hello Simon,

    A really great Script. Thanks for that. I’m not quite good in java and jquere,but i am on the way to learn it πŸ™‚ I like to use this kind of script but unfortunately I don’t know how to solve my problem.
    This is my problem:

    I have a Navigation where different pictures are listed by names. “Picture 1” “Picture 2” and so on… If somebody clicks on a name of the list the picture shall crossfade automatically into the new picture. The order of the pictures is not one after each other, it is open to the user which one is the next one. Similiar to the one with the control panel but when you click onto the link there should be the crossfade effect and the crossfade over the time is not necessary. I thought of doing it by the ID of the pictures but it did not actually work right now πŸ™
    Do you have an idea?? It would be fantastic.
    Thanks!

  312. Flash says:

    Thank you for the extra help, yes I didn’t have the jQuery included on my page and now it works perfectly.

  313. Simon says:

    Have a look at this demo. Have you included jQuery on your page? If this still doesn’t help drop me a link to your page.

  314. Flash says:

    I can’t get this tutorial to work at all. All my images are there on the browser but they just don’t fade. I am viewing it on IE9 amd Firefox 18 does it work on these? Can you help please?

  315. Simon says:

    No reason why that shouldn’t work. That sounds like you just haven’t set the height on #cycler – resulting it having no height because the images within it are absolutely positioned.

  316. Ian Haney says:

    Hi

    I am using this in a clients website and was just wondering how to add a border to the slideshow, I tried adding the following to the #cycler{ in the stylesheet but did not work, it only put a border at the top and then I had to put in a width percentage so would go all the way along the image but could not get the border to go all the way around the image

    Any ideas

    border: 5px solid #FFFFFF;

    Kind regards

    Ian

  317. Simon says:

    Multiple versions of jQuery loaded on your page? Any errors showing in your Firebug/Chrome console?
    Otherwise, no, can you send me a link to your page (I won’t publish it here).

  318. Anthony says:

    Hello Simon,

    I’m having a spot of bother, I have your script and an easySlider on my page, but after the first fade, it doesn’t continue. I tried what you suggested for mike, and it worked, but then the slider just wouldnt work.

    Do you have any suggestions off hand? Or do you need me to provide my coding?

  319. Simon says:

    Sito
    Not as is, because the images have a fixed width in pixels in the css. Amend this so that the width is set as a percentage and it should be OK. You don’t need to change the javascript.

  320. Sito says:

    Hello Simon,

    Can you tell me if I can use this script in a responsive HTML5/CSS3 website? will it adjust itself to the screen?

    regards!

  321. Peter says:

    Thanks for this, was great, I had a different need, which I got working because of this example. What I needed was for the images to crossfade but only on mouse hover, in addition, I wanted this to work no matter how many individual cycler divs i had.

    Now, im still pretty new to jQuery but I got it working like this (I dont know how to use code tags):

    function cycleImages( cycler ){
       var $active = $( cycler ).find( '.active' );
       var $next = ($active.next().length > 0) ? $active.next() : $( cycler ).find( 'img:first' );
    						
       //move the next image up the pile
       $next.css('z-index',2);
    						
       //fade out the top image
       $active.fadeOut(500,function(){
          //reset the z-index and unhide the image
          $active.css('z-index',1).show().removeClass('active');
          //make the next image the top one
          $next.css('z-index',3).addClass('active');
       });
    }
    			
    var intervalId;
    $( '.cycler' ).hover(
       function () {
          var cycler = this;
          intervalId = setInterval( function () {
             cycleImages( cycler );
          }, 1000);
       },
       function () {
          clearInterval( intervalId );
       }
    );
  322. Simon says:

    Lucas

    The browser, rather than the script, will load the images, all the script does is manipulate them for the slideshow. I assume what you’re trying to do is check after a certain period for an amended image? If so you could do this by running a periodic ajax call to retrieve the ‘latest’ images (using setTimeout() perhaps), and then just overwrite existing with new images every time.

  323. Lucas says:

    Hi Simon
    Thanks for a great little script! Hope you had a nice Christmas and New Year πŸ™‚
    If I have images loaded from a remote URL, is there a way for the script to check for an updated image, or to clear the script’s cache on a regular interval so it will load the images fresh?
    Cheers πŸ™‚

    Lucas

  324. Simon says:

    Steve

    You should be able to combine the controls and div examples – view the code on these pages to see how its done.

    If you want to add images for controls, that should be fine. You could either leave the javascript as it is and add the images as background images using css, or amend the controls javascript to include an image – call your images control1, control2 etc and then the javascript snippet should look something like:

    for (var j=0;j<=container.find('img').length-1;j++){
       container.find('.cycler_controls').append('<a class="page" href="#" rel="'+j+'"><img src="images/control'+(j+1)+'" alt="slide 1" /></a>');
    }
  325. Steve says:

    Hi Simon,

    First, thanks for putting this script together, I’ve been using it for a while and its amazing.

    Second, I’m looking to use the version with fading divs, but with controls. What modifications should be made to the code? Also, can images be used instead of numbers?

    Thanks for any help you can provide.

    Steve

  326. Simon says:

    The images need to be positioned absolutely so they’ll sit on top of each other. You can use left and top positioning on #cycler img if necessary to position the images.

  327. Jeff says:

    Thanks for the script, works perfectly!
    Just wondering, is their a way to have the images centered within the div instead of having the position fixed?

  328. Simon says:

    Markus

    Have a look at the variant with controls. This is almost what you want and could be simplified to allow progression on a click.

  329. Markus says:

    Hi and thanks for the easy and cool script!

    Is there a way to navigate with a click on the image to the next image?
    Cheers Markus

  330. Ruth says:

    Thanks! This is perfect for what I need!

  331. slammers says:

    Thank you so much for that, Simon! Exactly what I needed. And thanks also for the tip — I will add a conditional. πŸ™‚

  332. Simon says:

    Hi Steve

    It’s simple enough to adjust the script to what you describe, have a look here.
    View the source to see how it’s done.

    Of course, if your user does not have js enabled, a blank page will result.

  333. slammers says:

    Is there a way to adjust the script so that there is a delay between fadeIn & fadeOut?

    As in…

    – Blank Canvas
    – First image fades in
    – First image fades out
    – Delay
    – Second image fades in
    – ad infinitum

    Thanks, Simon! It’s such a marvelous script!

  334. Andrea says:

    Thank you Simon!
    That was one of those @.@ OOOOOOOOOHHHHHHHH moments!

  335. Simon says:

    Andrea

    If you have your images wrapped in anchor tags, then you need to amend the javascript slightly so it cycles through the a tags not the img tags.
    You’ll need to amend your css as well. Have a look at the example using divs, this should give you the idea.

  336. Andrea says:

    BRILLIANT SCRIPT! Thanks for that.
    But for some reason it breaks when I make the images into clickable links.
    Basically all I want is for the image to link to it’s corresponding website, so I have one slide each for Grills, Fireplaces, and HVAC and the href should just surround each image. But it breaks when I do that. Suggestions?

    THANK YOU! πŸ˜€

  337. Simon says:

    Firstly, I’d add the text within a paragraph tag within #portfolio_cycler, and position it with this css:

    #portfolio_cycler p{position:absolute;top:10px;right:10px;color:white;margin:0;z-index:4}

    Then a small change is needed to the javascript so the text isn’t faded. We just need to make it slightly more specific so it searches for the next img, not just the next element, when running the fades:

    function cycleImages(){
          var $active = $('#portfolio_cycler .active');
          var $next = ($active.next('img').length > 0) ? $active.next('img') : $('#portfolio_cycler img:first');
          $next.css('z-index',2);//move the next image up the pile
          $active.fadeOut(1500,function(){//fade out the top image
    	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
              $next.css('z-index',3).addClass('active');//make the next image the top one
          });
        }
    
    $(document).ready(function(){
    // run every 7s
    setInterval('cycleImages()', 7000);
    })

    Like this

  338. Dan says:

    Hi,
    How would I go about adding a static transparent overlay to the images. Basically I want it to stay put with a text description while the images fade.
    Thanks

  339. Simon says:

    Hi Kevin

    Use .find() to locate the image within the div (assuming there’s just one), or just set the rel attribute on the div rather than the image.
    To use .find() with your code:

    console.log($('.active').find('img').attr('src')+": "+$('.active').find('img').attr('rel'));
  340. Kevin says:

    Simon, thank you very much. I have one final question, then I think I’m good to go.

    I can’t quite figure out how to turn this part into using the divs. Obviously, a div doesn’t have a src. Would I use innerHTML instead? That didn’t seem to quite work…

    console.log($(‘div.active’).attr(‘src’)+”: “+$(‘div.active’).attr(‘rel’));

  341. Simon says:

    Kevin

    1. To use this on a div, just replace img with div throughout the javascript, and amend your html accordingly.
    2. To use variable timings, you first need to store the required time against the image (or div). You could do this by adding an (invalid) rel attribute, or use a (valid) data attribute if you’re using HTML5. Once this is done, then the function needs to be amended to work recursively so the variable timing can be used. Have a look at this demo to see how it might work.

  342. Kevin says:

    Awesome work, Simon. I have 2 questions:

    1. How can I make this work with divs instead.
    2. Is it possible to have different intervals between fades? (i.e. the ability to set an interval for each div/slide separately, as some may need to stay visible longer than others)

    Thanks,
    Kevin

  343. Robert says:

    Excellent snippet of code! Light & easy!!

  344. Simon says:

    If you have a look at the variations, and combine the ‘Cycle through images and stop’ and ‘Multiple cyclers with slideshow controls’ that should gove you what you need.

  345. Ajay says:

    Hello Simon,
    Thank you for posting this wonderful jQuery content, very beneficial.

    I was wondering if you could help me with this scenario:

    The crossfade galleries (2 of them, similar to your example) should not begin until start button is clicked, then at the end of the fade cycles, both should end, and have a replay button to replay them again.

    Thank you in advance, your help is greatly appreciated.

    Ajay

  346. Simon says:

    It’s straightforward to amend the cycling function to work on divs instead of images. Then you just need to either add a caption manually into the div, or possibly use the title attribute on the img element to hold the caption, and display it with javascript. In both cases you’ll need to position the caption as required within the div.

  347. Kevin Cramp says:

    Hi I am using web language for first time.
    on linux.
    want to slideshow header with landscapes and write different text over each photo…ie without editing each photo (may be easier)
    Is this possible?
    I have some initial “pile” code but don’t know how to use it as a show and as a function
    any help will be much appreciated.

  348. Simon says:

    Steve

    Have a look at this example. I think that meets your needs.

  349. Steve says:

    Hi Simon,

    Thanks a lot for this code, it’s managed to do wonders for my website (in process)

    I’m curious, is there a way to create a small numbering system so the viewer can choose which image they want to see. For example, the viewer comes to the page, the images being fading, but they can stop the fading by selecting a certain image, and then browse the image set manually.

    I don’t know if that makes sense or not.

    Thanks for any help you can provide.

  350. Simon says:

    Sathis87

    Have a look at this page to see how to adapt this to cycle a background image.

    Xemnes

    If you have pngs with transparent backgrounds then you can just add a plain background colour to the image via css to prevent other images showing.

  351. Xemnes says:

    hello there thanks for the script! im having one problem though, my images are logos and are pngs with alpha channels, on the page they show overlayed over each other, how do i get it so the image fades out and stays faded out until the other image has finished being displayed?

  352. sathis87 says:

    Hi,
    Thanks for useful tips.
    But can i knw how to set this as background.

  353. Simon says:

    Hi Todd

    Easiest is to set a background colour to the image, if your design allows it. If not then you’d need to amend the javascript so that the ‘next’ image is hidden, but fades in as the top image fades out.

  354. todd says:

    Hi, works great. My challenge is the images have transparency so they appear stacked. Anyways to arrange it so the back image is hidden?
    thanks todd

  355. Simon says:

    Hi Alexey

    Who’s Mike?
    Have a look at this using the same approach for a background.
    If your images are not visible that sounds like a css issue – check you have it correct.

    Simon

  356. Alexey says:

    sorry -)))

    one think all my blocks are invisible behind portfolio_cycler -(((

    do you have solution ? -)))

  357. Alexey says:

    Dear Mike, thx for a trick !!!

    It is possible to make it for resizable background (full screen) ?

    Thank you very much

  358. Simon says:

    Hi Mike

    You can do this by setting all the images except the top one to display:none via css:

    #portfolio_cycler{position:relative;}
    #portfolio_cycler img{position:absolute;z-index:1;display:none}
    #portfolio_cycler img.active{z-index:3;display:block}

    and then waiting until the page loads completely, before unhiding the images before running the cycle:

    $(window).load(function(){
    $('#portfolio_cycler img').show();
    // run every 7s
    setInterval('cycleImages()', 7000);
    })

    If there’s no javascript the images will stay hidden, but that won’t matter because the slideshow won’t function anyway.

  359. Mike Prince says:

    The initial load of the page however shows each image as they are being downloaded, and they overlay each other until fully downloaded. How can you avoid this?

  360. James Smyth says:

    Absolutely brilliant little snippet. Thanks a lot.

    Made a few edits for others who want to know how to make the images links.

    Simply wrap the images within the “portfolio_cycler” div in “a hrefs”.

    example –

    <a href="http://www.bbc.co.uk/"></a>

    Now replace the current code with this version.

    function cycleImages() {
        var $active = $('#portfolio_cycler a img.active');
        var $next = ($('#portfolio_cycler a img.active').closest('a').next().find('img').length > 0) ? $('#portfolio_cycler .active').closest('a').next().find('img') : $('#portfolio_cycler a:first img');
        $next.css('z-index', 2); 
        $active.fadeOut(1500, function () {
            $active.css('z-index', 1).show().removeClass('active');
            $next.css('z-index', 3).addClass('active');
        });
    }
    
    $(document).ready(function () {
    
        $('#portfolio_cycler a:first img').addClass('active');
        setInterval('cycleImages()', 2000);
    
    });

    Thanks a lot Simon for the original code!

  361. Marco says:

    Hi…
    I guess somewhere a reference to the jquery.js library has to be included…
    Thanks and bye.

  362. Hari says:

    Brilliant Simon !!!
    Worked perfectly on FF10 as well. Thanks a ton.

  363. Simon says:

    Thanks for your message.
    Hi Hari
    The problem you describe is not an issue with my code as such. It affects FF10 and FF11, on computers with graphic accelerators. I have a blog about it here. A workaround is to apply a background colour to the image – then the problem disappears.

  364. Hari says:

    Neat job, very simple to understand and works perfectly on most browsers. We used this idea in one of our works, but very few users did complain about seeing a black transparent overlay over the images during fade transitions in firefox. The same problem could not be reproduced on the same version of firefox on a different computer.

  365. Simon says:

    This needs a slight change to the code:

    function cycleImages(){
          var $active = $('#portfolio_cycler .active');
          var $next = ($('#portfolio_cycler .active').next().length > 0) ? $('#portfolio_cycler .active').next() : $('#portfolio_cycler img:first');
          $next.css('z-index',2);//move the next image up the pile
    	  $active.fadeOut(1500,function(){//fade out the top image
    	  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
          $next.css('z-index',3).addClass('active');//make the next image the top one
    	  if ($('#portfolio_cycler .active').next().length > 0) setTimeout('cycleImages()',7000);//check for a next image, and if one exists, call the function recursively
          });
        }
    
        $(document).ready(function(){
          // run every 7s
          setTimeout('cycleImages()', 7000);
        })

    Note this uses setTimeout() rather than setInterval().

  366. Stephanie says:

    Hi, Thanks so much for sharing your code! I found your code and had a quick question…how do I stop the cross fade at the last image?

  367. Simon says:

    Nicola

    You can view the source code of any web page yourself – Ctrl+U in everything except IE, Page > View Source in IE.

  368. Nicola says:

    hi, I’m really new to jquery (this is the first time I’ve attempted to use it!) I thank you for the simple language and explanation, but I’m unsure where to put the images and what code goes around them? I have a lot of images to interchange! Can you show your html with your image sources?

  369. He Simon,
    You saved my next 2hours and its very much simpler than what I thought.

    Thanks,
    Osama

  370. Erik says:

    Great script. Very helpful. I modified it to use divs instead of just images and also set it to run when an item is clicked rather than on a timer so it could be used as a product image gallery with sets of images per product. Thanks for getting me started.

  371. Kate says:

    Thank you Simon!

  372. Simon says:

    Hi Katka

    The revised html needs to be:

    function cycleImages(){
    	  $('.cycler').each(function(){
    		  var $active = $(this).find('.active');
    		  var $next = ($(this).find('.active').next().length > 0) ? $(this).find('.active').next() : $(this).find('img:first');
    		  $next.css('z-index',2);//move the next image up the pile
    		  $active.fadeOut(1500,function(){//fade out the top image
    			  $active.css('z-index',1).show().removeClass('active');//reset the z-index and unhide the image
    			  $next.css('z-index',3).addClass('active');//make the next image the top one
    		  });
    	  });
        }
    
        $(document).ready(function(){
          // run every 7s
          setInterval('cycleImages()', 7000);
        })

    with each div assigned a class of cycler instead of the id portfolio_cycler as in the main example.

  373. Kate says:

    Hello Simon, thank you! I’ve found what I need, thanks a lot.
    What is the correct way to have two of those crossfade effects on one page?

  374. Pam Hamilton says:

    Brilliant, Simon! I had accidently removed my js line in the head when got rid of an old rotator script that was too bloated. Thanks for making something simple…well, simple!

  375. Simon says:

    Hi David

    No – it should work fine however many images are stacked up.

  376. David says:

    This is neat. I am having some issues reproducing it. The way you set it up…it doesn’t matter how many images in the stack right?

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.