javascriptfadeinfadeoutfadetocross-fade

Adding fade function to JS script?


So I have this basic script which alternates between three images and I'd like to add a simple fadein/fadeout/fadeto or whatever looks best so it's not so clunky. How can I achieve this? Or, is there a better way?

function displayNextImage() {
    x = (x === images.length - 1) ? 0 : x + 1;
    document.getElementById("img").src = images[x];
    }
function displayPreviousImage() {
    x = (x <= 0) ? images.length - 1 : x - 1;
    document.getElementById("img").src = images[x];
    }
function startTimer() {
    setInterval(displayNextImage, 3000);
    }
    var images = [], x = -1;
    images[0] = "assets/img/logo1.png";
    images[1] = "assets/img/logo2.png";
    images[2] = "assets/img/logo3.png";

Solution

  • You can set the opacity of the images before you change the src:

    function displayNextImage() {
        x = (x === images.length - 1) ? 0 : x + 1;
        var imgvar = document.getElementById("img");
        imgvar.classList.add("fadeOut");
        setTimeout(function() {
            imgvar.src = images[x];
            imgvar.classList.remove("fadeOut");
        }, 500);
    }
    function displayPreviousImage() {
        x = (x <= 0) ? images.length - 1 : x - 1;
        var imgvar = document.getElementById("img");
        imgvar.classList.add("fadeOut");
        setTimeout(function() {
            imgvar.src = images[x];
            imgvar.classList.remove("fadeOut");
        }, 500);
    }
    function startTimer() {
        setInterval(displayNextImage, 3000);
    }
        var images = [], x = -1;
        images[0] = "assets/img/logo1.png";
        images[1] = "assets/img/logo2.png";
        images[2] = "assets/img/logo3.png";
    

    And in CSS:

    img {
         opacity: 1;
         transition: opacity 500ms ease-in-out;
    }
    img.fadeOut {
        opacity: 0;
    }
    

    Note: I added a 500ms timeOut in javascript because I suspect that otherwise the animation wouldn't be visible at all because it would instantly go from visible to invisible to visible again.