javascripthtmlcssslideshowcross-fade

How to crossfade images in .js slideshow


So this is my slideshow div:

<div class="header">
    <img name="slide" class="slide">
</div>

the css for it:

.slide{
    width: 80%;
    height: auto;
    filter: brightness(90%);
}

and the javascript:

var i = 0;
var images = [];
var time = 4000;


images[0] = '1.png';
images[1] = '2.png';
images[2] = '3.png';

function changeImg() {
  document.slide.src = images[i];

  if (i < images.length -1) {
    i++;

  }
  else
  {
    i = 0;
  }


  setTimeout("changeImg()", time);

}

window.onload = changeImg;

Now i want it to crossfade, currently its just switching the images very abruptly, but i want it smooth. Any help?


Solution

  • You need to add opacity set to 0 on your css class, and then create a new class with opacity set to 1, that way you'll trigger the function to switch opacity after a specific time period has passed

    <style>
        .slide {
            border: none; 
            opacity: 0; 
            position: absolute; 
            top: 0; 
            left: 0;
            -webkit-transition: opacity 2s linear;
            -moz-transition: opacity 2s linear;
            -o-transition: opacity 2s linear;
            transition: opacity 2s linear;
        }
        .visible {
            opacity: 1;
        }
    </style>
    
    <div class="header">
        <img id="img0" class="slide visible" src="1.png">
        <img id="img1" class="slide" src="2.png">
        <img id="img2" class="slide" src="3.png">
    </div>
    
    <script>
        var actual = 0;
        var total = 3;
    
        function addClass(elem, name) {
            elem.className = elem.className + " " + name;
        }
    
        function deleteClass(elem, name) {
            var c = elem.className;
            elem.className = c.replace(name, "").replace(/   /g, " ").replace(/^ | $/g, "");
        }
    
        function nextImg() {
            var e;
    
            e = document.getElementById("img" + actual);
            deleteClass(e, "visible");
    
            actual++;
            if (actual > total - 1) actual = 0;
    
            e = document.getElementById("img" + actual);
            addClass(e, "visible");
        }
    
        var slider = setInterval(nextImg, 4000);
    </script>