Marta Sampietro Marta Sampietro - 4 months ago 10
HTML Question

Image transition on click

I have a very simple HTML page with one image and one button. The idea is that, when the button is clicked, the image changes to another image. At the moment I have succeeded in changing the image when clicking the button by using the following javascript:

document.getElementById("img").src="img2.jpg";


However, I would like to know if there is some easy and simple way to make the change like a transition, for example a cross-fade between both images, with only javascript and css.

Answer

It can be done in step-by-step process:

  1. Create an img element at the same position of the original image.
  2. Increase the z-index of said element
  3. Hide the element
  4. Add element into the DOM
  5. Fade it slowly into the view.

See the WORKING SNIPPET BELOW:

function act() {
  var element = document.createElement("img");
  element.src = "http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg";
  var op = 0.1; // initial opacity
  element.style.opacity = op;
  document.body.appendChild(element);
  element.style.display = 'block';
  var timer = setInterval(function() {
    if (op >= 1) {
      clearInterval(timer);
    }
    element.style.opacity = op;
    element.style.filter = 'alpha(opacity=' + op * 100 + ")";
    op += op * 0.1;
  }, 50);
}
img {
  position: absolute;
  top: 30px;
  left: 0px;
  width: 300px;
  height: 300px;
}
<button onclick='act()'>FADE CHANGE</button>
<br />
<img id="img" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/200/287.jpg">