I am having some troubles trying to crossfade a slideshow with images. These images are displayed by the background-img attribute.
When I use the .fadeOut() and .fadeIn() functions the image first fades into nothing before it displays the next image.
I have tried solving this with the .load() function but that didn`t seem to work.
Here is my code:
mySlider.js:
var slides = [
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider13.png"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider10.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider9.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider3.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider4.png"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider2.png"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider11.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider12.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider1.png"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider5.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider7.jpg"
},
{
url: "#",
src: "http://localhost:8888/Imprez_v2/wp-content/uploads/2018/11/slider8.jpg"
}
]
myScript.js:
const initiateSlider =()=> {
console.log("initiateSlider");
$("#mySlider").css('background-image', 'url(' + slides[0].src + ')');
$("#mySlider").data('sld','0');
setTimeout(nextSlide, 5000); // voert nextSlide 1x uit na x seconden
}
const nextSlide =()=> {
console.log("nextSlide");
let currentSlide = $("#mySlider").data('sld');
$("#mySlider").data('sld', parseInt(currentSlide) + 1);
let newSlideIndex = $("#mySlider").data('sld');
console.log(newSlideIndex);
if(newSlideIndex < slides.length)
{
$("#mySlider").css('background-image', 'url(' + slides[newSlideIndex].src + ')');
setTimeout(nextSlide, 5000);
}
else {
initiateSlider();
}
}
As you've said, the main issue is that when the image fades out, nothing is behind it. You will need to position the next image under the first image, so that when the first image fades out, you can slowly see the image behind it. Then, after the fade out is complete, move that image to the back of the line.
So in this example, what I do is have two divs who are position exactly on top of one another. This is done with
position: absolute;. Then I fade out the top one, so the bottom one is showing, then move the top one to the bottom, change it's image, and reset it's styles. At this point the other image is on top, and I just fade that one out.JS Fiddle Demo