I am trying to add a fade effect to this JavaScript

Could you help me to add a fade effect to this script?

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, 8000);
}

Hi there minermichilpinhd,

and a warm welcome to these forums. :winky:

You cannot fade between display: block and display: none. :unhappy:

There is no transition, it is either one or the other.

Perhaps you you should look into the possibility of using opacity: 1 and opacity: 0.

You don’t even need JavaScript as CSS is quite good at this sort of thing…

<!DOCTYPE html>
<html lang="en">
<head>
<base href="http://coothead.co.uk/images/">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>untitled document</title>

<style media="screen">
body {
    background: #f0f0f0;
    background-image: linear-gradient(to bottom,#fff,#ccc);
    background-attachment: fixed;
 }

#container {
    position: relative;
    width: 40%;;
    padding-top: 23.6%;
    margin: 1em auto;
    border: 0.06em solid #999;
    box-shadow: 0.4em 0.4em 0.4em #999;
    overflow: hidden;
 }

#container img {
    position: absolute;
    top: 0;
    width: 100%;
    height: auto;
    animation: round 40s infinite;
    opacity: 0;
 }

#container img:nth-child(1)  { animation-delay: 36s; }
#container img:nth-child(2)  { animation-delay: 32s; }
#container img:nth-child(3)  { animation-delay: 28s; }
#container img:nth-child(4)  { animation-delay: 24s; }
#container img:nth-child(5)  { animation-delay: 20s; }
#container img:nth-child(6)  { animation-delay: 16s; }
#container img:nth-child(7)  { animation-delay: 12s; }
#container img:nth-child(8)  { animation-delay: 8s;  }
#container img:nth-child(9)  { animation-delay: 4s;  }
#container img:nth-child(10) { animation-delay: 0s;  }

@keyframes round {
10% {
    width: 100%;
    margin-top: 0;
    margin-left: 0;
    opacity: 1; 
    transform: rotateY(0deg);
  }

20% {
    width: 200%;
    margin-top: -50%;
    margin-left: -50%;
    opacity: 0; 
    transform: rotateY(90deg);
  }
 }
</style>

</head>
<body> 

<div id="container">
 <img src="face-8col.jpg" alt="">
 <img src="face-8.jpg" alt="">
 <img src="people-2col.jpg" alt="">
 <img src="people-2.jpg" alt="">
 <img src="face-3col.jpg" alt="">
 <img src="face-3.jpg" alt="">
 <img src="people-1col.jpg" alt="">
 <img src="people-1.jpg" alt="">
 <img src="face-7col.jpg" alt="">
 <img src="face-7.jpg" alt="">
</div>

</body>
</html>

coothead

3 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.