I have a full screen slideshow of four images (in an array) that loads/starts at a random image then cycles through the rest of the images with fade ins. My problem is the fade ins do not fade over the previous image, but fades in from white (or a background color if/when added). I would like a crossfade wherein new image and current image fade smoothly in and out respectively, but I’m at a loss. I can create a crossfading slideshow without a random starting point, so I’m familiar with javascript to CSS, but the javascript code that I’ve stitched together for the added random start has me flailing. I’ve spent hours on stack overflow going through similar issues but none have done the job. My ignorance in javascript is definitely an issue, but I’m usually capable enough to get done what I need to get done. Any help is greatly appreciated, with JS fiddles and-or notes if possible. Thanks in advance, code as follows:
const images = [
"hero-1.jpg",
"hero-2.jpg",
"hero-3.jpg",
"hero-4.jpg",
];
const imgElement = document.getElementById("myImage");
let currentIndex;
function fadeInImage(index) {
imgElement.style.opacity = 0;
imgElement.src = images[index];
let opacity = 0;
imgElement.style.opacity = opacity;
const intervalId = setInterval(() => {
opacity += 0.01;
imgElement.style.opacity = opacity;
if (opacity >= 1) {
clearInterval(intervalId);
}
}, 20);
currentIndex = index;
}
function playImages() {
let randomIndex = Math.floor(Math.random() * images.length);
fadeInImage(randomIndex);
setInterval(() => {
currentIndex = (currentIndex + 1) % images.length;
fadeInImage(currentIndex);
}, 5000);
}
playImages();
body,
html {
height: 100%;
margin: 0;
padding: 0px;
outline: none;
border: 0px;
}
.homehero {
height: 100%;
}
.homehero img {
height: 100%;
width: 100%;
object-fit: cover;
}
<div class="homehero"><img id="myImage" alt="" /></div>

