Search code examples
jqueryslideshowfadein

Simple jQuery Slideshow with fadein/fadeout


I have this really simple jQuery Slideshow: http://jsfiddle.net/6zA4B/

HTML:

<div class="fadein">
<img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg">
<img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg">
<img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg">
</div>

JavaScript:

​$(function(){
    $('.fadein img:gt(0)').hide();
    setInterval(function(){$('.fadein :first-child').fadeOut().next('img').fadeIn().end().appendTo('.fadein');}, 3000);
});​

It works perfectly, I just want to replace the 3 img tags with 3 divs (so I can include a caption below the images). How can I modify the script to achieve that? I tried with this but probably I'm doing something wrong...

HTML:

<div class="fadein">
    <p><img src="http://farm3.static.flickr.com/2610/4148988872_990b6da667.jpg">image1</p>
    <p><img src="http://farm3.static.flickr.com/2597/4121218611_040cd7b3f2.jpg">image2</p>
    <p><img src="http://farm3.static.flickr.com/2531/4121218751_ac8bf49d5d.jpg">image3</p>
</div>

JavaScript:

$(function(){
    $('.fadein p:gt(0)').hide();
    setInterval(function(){$('.fadein :first-child').fadeOut().next('p').fadeIn().end().appendTo('.fadein');}, 3000);
});​

http://jsfiddle.net/S4SmM/1/ :D


Solution

  • One of your selectors is slightly off:

    $('.fadein :first-child')
    

    Is selecting all elements that are first children underneath .fadein. This includes the first child of the p elements, which are the images you're trying to rotate to.

    You want to restrict the :first-child selector to elements directly under .fadein. One way would be to use the child selector:

    $('.fadein > :first-child')
    

    Example: http://jsfiddle.net/S4SmM/4/