79556394

Date: 2025-04-04 23:59:10
Score: 0.5
Natty:
Report link

Thanks again for the assist. Using provided input I went in a different direction and believe I have a working solution. I'm posting code here for others who might find it helpful. I would suggest preloading these images (especially if using for a header/hero option else the first loop will probably appear wonky. Once images are loaded, crossfades are smooth and a random image is served as site starting point (to then run through remaining images in array). I'm sure there are other ways to achieve this, but feel free to throw out any red-flag warnings I should consider.

<!DOCTYPE html>
<html>
<head>
<title>random start slideshow</title>

<style>

.upper {
position: absolute;
z-index: 1;
width: 500px;
height: 300px;
}

.upper img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}

.upper img.active { opacity: 1; }

.lower {
position: relative;
width: 500px;
height: 300px;
}

.lower img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}

.lower img.active { opacity: 1; }

</style>
</head>
<body>

<div class="upper" id="container1"></div>
<div class="lower" id="container2"></div>

<script>

const images = [
"https://picsum.photos/id/650/1000",
"https://picsum.photos/id/651/1000",
"https://picsum.photos/id/652/1000",
"https://picsum.photos/id/653/1000",
];

const container1 = document.getElementById('container1');
const container2 = document.getElementById('container2');

let currentIndex = Math.floor(Math.random() * images.length);
let nextIndex;

function showImage(container, index) {
const img = document.createElement('img');
img.src = images[index];
img.onload = () => {
container.appendChild(img);
setTimeout(() => {
img.classList.add('active');
}, 5);
};
}

function crossfadeImages() {
nextIndex = (currentIndex + 1) % images.length;
showImage(container2, nextIndex);
const currentImage = container1.querySelector('img');
if (currentImage) {
currentImage.classList.remove('active');
currentImage.addEventListener('transitionend', () => {
currentImage.remove();
container1.innerHTML = container2.innerHTML;
container2.innerHTML = '';
currentIndex = nextIndex;
setTimeout(crossfadeImages, 4000);
}, { once: true });
} else {
container1.innerHTML = container2.innerHTML;
container2.innerHTML = '';
currentIndex = nextIndex;
setTimeout(crossfadeImages, 4000);
}
}

showImage(container1, currentIndex);
setTimeout(crossfadeImages, 4000);

</script>
</body>
</html>
Reasons:
  • Blacklisted phrase (0.5): Thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: SJR