Search code examples
javascriptcsscss-transitionsfadein

How to make an image change to another one with a transition effect using vanilla Javascript?


on a website I'm creating I have some accordions, and each of them has an image at the top. When you open the accordion, there's a description inside, and the image changes to another one. Then when you close the accordion, the image switches back to the first one. The problem is that I'd like this image change to have a smooth transition, with a fade effect, and right now it's just an abrupt change. How can I do it?

Let's say that the accordion button has an id of "button"; and the tag that contains the first image (which will change to the second image) has an id of "firstimage".

This is the code in Javascript:

let counter = 1;

let button = document.querySelector("#button");
button.addEventListener("click", function () {
  let image = document.querySelector("#firstimage");
  image.setAttribute(
    "src",
    "(url of the first image)"
  );
  counter++;
  if (counter > 2) {
    counter = 1;
    image.setAttribute(
      "src",
      "(url of the second image)"
    );
  }
});

Maybe this is something I should edit in the CSS? I already tried adding a transition to the first image in CSS ( transition: all 360ms ease-in-out ) but it didn't work.


Solution

  • You can just put two images on top of one another and set the opacity.

    document.querySelector('.wrapper').addEventListener("click", function (e) {
      e.currentTarget.classList.toggle("active");
    });
    .wrapper {
      position: relative;
      display: inline-block;
    }
    
    .wrapper > img + img {
      position: absolute;
      left:0;
      opacity: 0;
      transition: opacity 2s ease-in-out;
    }
    
    .wrapper.active > img + img {
      opacity: 1;
      transition: opacity 2s ease-in-out;
    }
    <div class="wrapper">
      <img src="http://placekitten.com/200/300" />
      <img src="http://placekitten.com/g/200/300" />
    </div>