skip to Main Content

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>

2

Answers


  1. 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>
    Login or Signup to reply.
  2. I was just about to answer as well

    check this link and the code is in the bottom there is a button that will transfer you to the editor

    enter image description here

    https://lr94yk-1234.csb.app/

    code :

    codesandbox code link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search