Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Automatic slideshow fade?

Hi guys,

I have created an automatic slideshow containing 3 images with the class "mySlides" these are placed inside of a div. My Jquery code is below...how would i add a fade to the images like this...http://www.jssor.com/slideshow/x-fade.html

$(document).ready(function(){
var slideIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
      x[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > x.length) {slideIndex = 1}
    x[slideIndex-1].style.display = "block";
    setTimeout(carousel, 5000); // Change image every 2 seconds
}
});

Thanks in advance!

1 Answer

Steven Parker
Steven Parker
229,981 Points

Did you sign up on that site you linked to? It looks like you can build your own effects and download the code. Even without signing up, you can download the code for the demos. There's some really cool stuff there!

You didn't share your HTML or CSS, but assuming the images are all absolutely positioned over each other, and initially display: none, for just a simple crossfade you could do something like this:

$(function() {
    var slides = $(".mySlides");
    var slideIndex = 0;
    carousel();

    function carousel() {
        slides.eq(slideIndex).fadeOut(1000);
        slideIndex = ++slideIndex % slides.length;
        slides.eq(slideIndex).fadeIn(1000);
        setTimeout(carousel, 5000); // Change image every 5 seconds
    }
});