Search code examples
javascriptcssfadeinfadeout

CSS3 Slide Show Fade Effect not working


http://jsfiddle.net/pdb4kb1a/2/

The code works just fine on JSFiddle, but I cant get it to work when I use it in a HTML/CSS file. Only the 50x200 image is displayed, no signs of the simple slideshow or fade effect. I work in Sublime text, could that create any problems?

var imgArray = [
    'http://placehold.it/300x200',
    'http://placehold.it/200x100',
    'http://placehold.it/400x300'],
    curIndex = 0;
    imgDuration = 3000;

function slideShow() {
    document.getElementById('slider').className += "fadeOut";
    setTimeout(function() {
        document.getElementById('slider').src = imgArray[curIndex];
        document.getElementById('slider').className = "";
    },1000);
    curIndex++;
    if (curIndex == imgArray.length) { curIndex = 0; }
    setTimeout(slideShow, imgDuration);
}
slideShow();
#slider {
    opacity:1;
    transition: opacity 1s; 
}

#slider.fadeOut {
    opacity:0;
}
<body> 
<img id="slider" src="http://placehold.it/50x200">
</body>


Solution

  • JSFiddle executes the javascript code in the window.onload event. You can change this if you click the JavaScript Button in the editor of JSFiddle. If you change it to No wrap - in <head> you'll see that it doesn't work as well. You should see an error in your console, telling you the reason.

    I'm assuming that you're including your script snippet in the head section of your HTML Document.

    If you take your code as posted in your question, your slider isn't loaded yet, because the script is executed before your HTML document is fully loaded. You have to wrap the call to your slideShow function inside the onloadevent (or if you're using jQuery you'll probably use $(document).ready(function(){ ... }) instead.

    This should do the trick then:

    window.onload = function() {
        slideShow();
    }
    

    Including the script at the bottom of your HTML document should work as well as an alternative.