search

Home  >  Q&A  >  body text

Implement transition effects for image replacement using pure Javascript

On a website I created, I have a number of accordions, each with an image on top. When you open the accordion, there is a description inside and the image changes to another. Then when you close the accordion, the image switches back to the first image. The problem is that I want this image change to have a smooth transition, with a fade effect, whereas now it's just a sudden change. what should I do?

Suppose the accordion button has an id of "button"; the label containing the first image (which will be changed to the second image) has an id of "firstimage".

This is the JavaScript code:

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've tried adding a transition in CSS to the first image (transition: all 360 ms ease in and out) but it doesn't work.

P粉458913655P粉458913655319 days ago488

reply all(1)I'll reply

  • P粉345302753

    P粉3453027532024-03-30 11:14:29

    You can overlay two images on top of each other 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;
    }

    reply
    0
  • Cancelreply