Marta Sampietro Marta Sampietro - 4 months ago 11
CSS Question

Cross-Fade 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 a 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:

SOLN 1: using pure Javascript & filter: alpha without CSS3 for even old browsers like IE-5+:

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 + ")"; // IE 5+ Support
    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">

SOLN 2: Alternate soln with CSS3 Transitions for IE10+, Chrome 26+, Fx 16+, Op 12.1+ :

var element = document.createElement("img");
element.src = "http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg";
document.body.appendChild(element);
element.style.opacity = 0;
element.style.transition = "opacity 1s";

function act() {
  element.style.opacity = 1;
}
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">

Note: I haven't been able to actually test in really old browsers like IE 6 but theoretically should work well. Comment if you find a discrepancy.