Implement transition effects for image replacement using pure Javascript
P粉458913655
P粉458913655 2024-03-30 00:14:11
0
1
408

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粉458913655
P粉458913655

reply all(1)
P粉345302753

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;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template