I’m trying to get the background image of a certain div, to change/cycle through an array of images using the following code.
It works as supposed, only thing is i have no idea how to implement a fade in/fade out transition effect when it comes to js. Tried in CSS, but it only affects the very first load of the first image, when the whole page is loaded.
Could you please help me implement a fade transition between images?
function displayNextImage() {
x = (x === images.length - 1) ? 0 : x + 1;
document.getElementById("slider-background").src = images[x];
}
function changeImage() {
setInterval(displayNextImage, 5000);
}
var images = [], x = -1;
images[0] = "https://www.example.com/1.jpg";
images[1] = "https://www.example.com/2.jpg";
images[2] = "https://www.example.com/3.jpg";
2
Answers
Okay so first you’ll need to update your css with this id:
Next, you’ll need to add quite some stuff in ur javascript file. I commented everything so I hope it’s understandable.
The code makes a picture slowly vanish, then waits a bit, switches to a new picture, and makes that picture slowly appear. It makes sure the timing matches up so it looks smooth.
Other solution (include using opacity and preloading images):