Marta Sampietro Marta Sampietro - 1 year ago 63
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:


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 Source

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.


function act() {
  var element = document.createElement("img");
  element.src = "";
  var op = 0.1; // initial opacity = op;
  document.body.appendChild(element); = 'block';
  var timer = setInterval(function() {
    if (op >= 1) {
    } = op; = '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="">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download