Search code examples
htmlcssimageanimationwebkit

Images don't blend out during CSS transition


My specific issue is that images suddenly disappear before the next image transitions in during a slideshow style image switch.

The whole slideshow works fine, just that sudden disappearance of each image before the next image fades in is rather disconcerting.

I'm a beginner and have no JQuery experience so wondering if I should be using something different than webkit animation.

Html:

<div class="pimgSlideshow"; style="max-width:500px">
<img class="mySlides fade" src="../images/pic1.jpg" style="width:100%">
<img class="mySlides fade" src="../images/pic2.jpg" style="width:100%">
<img class="mySlides fade" src="../images/pic3.jpg" style="width:100%">
</div> 

CSS:

.mySlides {display:none;
}

.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  -webkit-animation-timing-function: ease-in-out;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .5} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .5} 
  to {opacity: 1}
}

JS:

var myIndex = 0;
carousel();

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

Solution

  • Rather than using CSS animation you would do better to use a CSS transition instead, replacing the display:none; in the javascript with opacity ="0" and opacity ="1" respectively.

    Also by positioning the images absolutely they will appear as if on top of each other as they fade in and out.

    Updated JS:

    var myIndex = 0;
    carousel();
    
    function carousel() {
        var i;
        var x = document.getElementsByClassName("mySlides");
        for (i = 0; i < x.length; i++) {
            x[i].style.opacity = "0";  
        }
        myIndex++;
        if (myIndex > x.length) {myIndex = 1}    
        x[myIndex-1].style.opacity = "1";  
        setTimeout(carousel, 5000);
    }
    

    CSS

    .pimgSlideshow {
        position: relative;
    }
    
    .mySlides {
        display:block;
        transition: ease all 1s;
        position: absolute;
        left: 0;
        top: 0;
    }
    

    See this fiddle to demonstrate: http://jsfiddle.net/c8uaqk31/19/