I want to make few images displaying as slides with fadeIn effect in css. Everything works fine, images are displayed in 3s period with setInterval javascript method, but only first image displays with fadeIn animation.
.slide {
position: absolute;
height: 100vh;
width: 66vw;
animation: fadeIn 1s;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<img src="https://static.vecteezy.com/packs/media/components/global/search-explore-nav/img/vectors/term-bg-1-666de2d941529c25aa511dc18d727160.jpg">
There is only one jpg added to HTML and javascript code is written to replace file path from
<img src="1.JPG">
to "2.jpg", "3.jpg" etc
Only first image has animation, everything displayed later is without animation.
When I check console, all next images still have .slide class and all its properties position/width/height/animation, but they display without animation.
Any ideas ?
CodePudding user response:
Basically, you need to trigger the css
animation every time you change the src
. You can do it by removing the element class, triggering a DOM reflow, and adding the class again. But you should be careful because triggering reflow can be an expensive operation. Read more about it here.
const images = [
"https://via.placeholder.com/300?text=image1",
"https://via.placeholder.com/300?text=image2",
"https://via.placeholder.com/300?text=image3",
];
const img = document.querySelector(".slide");
let imageIndex = 0;
const imageInterval = setInterval(() => {
imageIndex ;
if (imageIndex >= images.length) {
clearInterval(imageInterval);
} else {
img.src = images[imageIndex];
img.classList.remove("slide");
void img.offsetWidth; // trigger a DOM reflow
img.classList.add("slide");
}
}, 3000);
.slide {
position: absolute;
height: 100vh;
width: 66vw;
animation: fadeIn 1s;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<img src="https://via.placeholder.com/300?text=image1">
CodePudding user response:
Hard to tell what exactly you want but with pure CSS perhaps something like this
.slide {
position: absolute;
opacity: 0;
height: 100vh;
width: 66vw;
animation: fadeIn 1s forwards;
}
.two {
animation-delay: 3s;
}
.three {
animation-delay: 6s;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<img src="https://static.vecteezy.com/packs/media/components/global/search-explore-nav/img/vectors/term-bg-1-666de2d941529c25aa511dc18d727160.jpg">
<img src="https://compote.slate.com/images/f063a07e-e5ab-4e04-8093-281d0a28ebe8.jpeg">
<img src="https://i.ytimg.com/vi/nWLUdoK5fSs/maxresdefault.jpg">