I'm trying to create a carousel using just HTML, CSS and JS.
It works, but not as well as I was hoping for.
When it finishes one round of images, it takes roughly 8 seconds to start showing the images from the first to the last one, and then it stops again for several seconds and so on...
Additionally, the div containing the background-images is 100% width and 100vh height. I've tried to set the background properties like bg-repeat, bg-size, bg-position, but I can't manage to get the images to display well on the screen - They images become cropped when set background-size: cover, and become too small if I set background-size: contain; or another property.
Can you please check this "working" demo? Thanks.
var divi = document.querySelector(".divi");
srcArr = ["https://picsum.photos/id/237/200/300", "https://picsum.photos/id/238/200/300", "https://picsum.photos/id/239/200/300", "https://picsum.photos/id/240/200/300"];
var iter = 0;
setInterval(function() {
if (iter == (srcArr.length)) {
iter = 0;
} else {
divi.style.backgroundImage = "url('" + srcArr[iter] + "')";
iter++;
}
}, 4000);
* {
padding: 0;
margin: 0
}
.divi {
width: 100%;
height: 100vh;
background-image: url("https://picsum.photos/id/240/200/300");
background-repeat: no-repeat;
-webkit-background-size: cover;
background-size: cover;
}
<div class="divi"></div>
ifstatement:if (iter == (srcArr.length)). Only if it is false do you change the image:divi.style.backgroundImage = "url('" + srcArr[iter] + "')";. This means that, if that statement is true, the image will not change for another 4 seconds.