I want to create a fade in/out carousel. Everything works fine but the image appears instantly instead of fading in
// JavaScript for the fade carousel
const slides = document.querySelectorAll('.carousel-slide');
let currentSlide = 0;
// Show the first slide initially
slides[currentSlide].style.display = 'block';
function nextSlide() {
slides[currentSlide].style.display = 'none';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].style.display = 'block';
}
// Automatically switch slides every 3 seconds
setInterval(nextSlide, 3000);
.carousel-container {
position: relative;
max-width: 600px;
margin: auto;
overflow: hidden;
}
.carousel-slide {
display: none;
width: 100%;
height: 100%;
}
<div class="carousel-container">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Nurses" alt="Slide 1">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Barbers" alt="Slide 2">
<img class="carousel-slide" src="https://fakeimg.pl/600x200?text=Receptionist" alt="Slide 3">
</div>
Just use opacity and css transitions. You can also listen to transitionend
event if you need more control.
// JavaScript for the fade carousel
const slides = document.querySelectorAll('.carousel-slide');
let currentSlide = 0;
// Show the first slide initially
slides[currentSlide].style.opacity = '1';
function nextSlide() {
slides[currentSlide].style.opacity = '0';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].style.opacity = '1';
}
// Automatically switch slides every 3 seconds
setInterval(nextSlide, 3000);
.carousel-container {
position: relative;
max-width: 600px;
margin: auto;
overflow: hidden;
width: 100%;
aspect-ratio: 16/9;
}
.carousel-slide {
width: 100%;
height: 100%;
transition: opacity 1s ease-out;
opacity: 0;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
<div class="carousel-container">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Nurses" alt="Slide 1">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Barbers" alt="Slide 2">
<img class="carousel-slide" src="https://fakeimg.pl/600x400?text=Receptionist" alt="Slide 3">
</div>