I cannot get this slideshow to work fine in every img.
After tweaking it for hours I reached the conclusion that the problem has something to do with timing and the classes swaping at the same time for all the elements, but I cannot find a way to solve the problem.
let slideIndexPrev = 1;
let slideIndexCurr = 0;
showSlides();
function showSlides() {
let slides = document.getElementsByClassName("mySlides");
if (slideIndexPrev >= slides.length) {slideIndexPrev = 0}
if (slideIndexCurr >= slides.length) {slideIndexCurr = 0}
slides[slideIndexCurr].classList.add("fade-in");
slides[slideIndexCurr].classList.remove("fade-out");
slides[slideIndexPrev].classList.add("fade-out");
slides[slideIndexPrev].classList.remove("fade-in");
slideIndexPrev ;
slideIndexCurr ;
setTimeout(showSlides, 3000); // Change image every X seconds
}
* {box-sizing:border-box}
/* Slideshow container */
.slideshow-container {
display: flex;
position: relative;
min-width: 100%;
min-height: 250px;
border-bottom: 2px solid #333;
}
.mySlides img {
display: flex;
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
/* Fading animation */
.fade-in {
animation-name: fade-in;
animation-duration: 2s;
}
.fade-out {
animation-name: fade-out;
animation-duration: 2s;
}
@keyframes fade-in {
from {opacity: 0}
to {opacity: 1}
}
@keyframes fade-out {
from {opacity: 1}
to {opacity: 0}
}
<!-- Slideshow container -->
<div >
<!-- Full-width images -->
<div >
<img src="https://ca- times.brightspotcdn.com/dims4/default/f652f70/2147483647/strip/true/crop/5389x3153 0 0/resize/1486x869!/quality/90/?url=https://california-times-brightspot.s3.amazonaws.com/a9/5b/c621f3bc408e95c16b4538d87578/la-photos-1staff-amazonstudios-210802a.jpg"
style="object-position: 50% 40%;">
</div>
<div >
<img src="https://i.pinimg.com/originals/c5/6b/d1/c56bd1d016ccd315aa9e8d3ec3c78bb7.png"
style="object-position: 50% 47%;">
</div>
<div >
<img src="https://wallpaperaccess.com/full/3203467.jpg"
style="object-position: 50% 51%;">
</div>
Thanks in advance for any help provided!
CodePudding user response:
- You currently have two elements with
fade-in
and one withfade-out
- take a look at the console. So you probably want to swap those in js to have something like this:
slides[slideIndexCurr].classList.add("fade-out");
slides[slideIndexCurr].classList.remove("fade-in");
slides[slideIndexPrev].classList.add("fade-in");
slides[slideIndexPrev].classList.remove("fade-out");
- When the animation is over, opacity goes back to 1. So it fades, and then suddenly reappears. Simply add
opacity: 0;
to yourfade-out
class.
See the pen: https://codepen.io/rajniszp/pen/RwQpmZR
If I helped, vote up is appreciated :D