Search code examples
javascriptimagetransitionslideshowopacity

Trying to make a transition with opacity on images


like my title says, I'm trying to make a transition with opacity (0 to 1 with 2secondes interval) on images, but I don't know how to make it.

The transition only works on the first image but not on the others, and I can't figure it out why.

So I hope you'll help me to understand my mistakes, I'm new on javascript. Thank you in advance, here my code

My HTML file :

<img src="img/1.jpg" alt="slide-photo">

My CSS file :

#slideshow-home img {
    width: 100%;
    opacity: 0;
    transition: 1s ease-in-out;
}

My JS file :

var image = document.querySelector('img');
var img = 1 ;

window.setInterval(changeImage, 2000); 

function changeImage() {
    image.setAttribute('src', 'img/' + img + '.jpg'); 
    image.style.opacity = 1; 
    img++; 
    if(img === 6) { 
        img = 1; 
    }
}

Solution

  • This is how i handle fade in transitions for images, the benefit is it doesn't start until the image has actually been loaded so it should never be choppy while fading in

    JS

    var image = document.querySelector('img');
    var img = 1;
    
    window.setInterval(changeImage,5000); 
    
    function changeImage() {
        image.classList.remove('fadeIn')
        image.src = 'img/'+img+'.jpg'
        img++
        if (img == 6) {
          img = 1;
        } 
    }
    
    image.addEventListener('load', () => { // This function looks at the image and every time an image is loaded i.e whenever it gets a new src, it does a fade in animation
      void(image.offsetHeight)
      image.classList.add('fadeIn')
    })
    

    CSS

    I normally do this with an animation, like below

    #slideshow-home img {
        width: 100%;
        opacity: 0;
    }
    
    @keyframes fadeIn {
      0% {
        opacity: 0;
      }
    
      100% {
        opacity: 1;
      }
    }
    
    .fadeIn {
      animation:fadeIn 2s forwards;
    }