To continue on my previous question I would like to have my slideshow change the slides only when the picture has loaded up. I tried the following, but it doesn't appear to work as intended, because it just skips the slides at start:
HTML:
<div style="margin-bottom: 30px;">
<img class="slider" src="graphics/slider1.webp" onload="changeSlide(1);">
<div class="slider-text" id="slidert1">Text here.</div>
<img loading="lazy" class="slider" src="graphics/slider2.webp" onload="changeSlide(1)">
<img loading="lazy" class="slider" src="graphics/slider3.webp" onload="changeSlide(1)">
<img loading="lazy" class="slider" src="graphics/slider4.webp" onload="changeSlide(1)">
<img loading="lazy" class="slider" src="graphics/slider5.webp" onload="changeSlide(1)">
<img loading="lazy" class="slider" src="graphics/slider6.webp" onload="changeSlide(1)">
<button class="slider-button slider-black slider-display-left" onclick="changeSlide(-1)">❮</button>
<button class="slider-button slider-black slider-display-right" onclick="changeSlide(1)">❯</button>
</div>
JS:
var slideIndex = 0;
document.querySelector('.slider').forEach(function(img){
img.addEventListener('load', changeSlide(1);
});
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("slider");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
slideIndex++;
if (slideIndex > x.length) {slideIndex = 1}
x[slideIndex-1].style.display = "block";
setTimeout(carousel, 5000); // Change image every 5 seconds
}
function changeSlide(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("slider");
if (n > x.length) { slideIndex = 1 }
if (n < 1) { slideIndex = x.length }
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
x[i].style.width = "100%";
}
x[slideIndex - 1].style.display = "block";
}
The use case for this code is when a mobile user with a very slow 2G connection starts downloading pictures the slides start switching before the image has finished loading. Thereby was the solution with onload implemented so that the switching starts only (after a delay) when the image is fully loaded.