0

I have a simple function to replace one image with others using JavaScript. And I have one line to fade in it when loading. But how can I add a fade in when the new image is displayed?

<script type="text/javascript">
function changeImage(a) {
 document.getElementById("Image").src = a;
}
</script>

<div>
 <img src="Mini-01.jpg" onclick="changeImage('Photo-01.jpg');">
 <img src="Mini-02.jpg" onclick="changeImage('Photo-02.jpg');">
</div>

<div>
  <img id="Image" src="Photo-01.jpg" onload="this.style.animation='fadein 2s'">
</div>

I tried using:

onchange="this.style.animation='fadein 2s'"

but it does not work.

I think it is too simple to use Jquery on this case.

Can you please helm me?

Rafael
  • 193
  • 1
  • 11
  • Possible duplicate: http://stackoverflow.com/questions/23244338/pure-javascript-fade-in-function – Troyer Nov 23 '16 at 15:50

2 Answers2

1

You can write custom function for fadeIn like this:

function fadeIn(el) {
  el.style.opacity = 0;


  var tick = function() {
    el.style.opacity = +el.style.opacity + 0.01;


    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16)
    }
  };

  tick();
}
//taken from http://stackoverflow.com/questions/23244338/pure-javascript-fade-in-function

function changeImage(a) {
    var el = document.getElementById("Image");
    el.src = a;
    fadeIn(el)
}

where el = document.getElementById() or something.

Here is https://jsfiddle.net/60x3bo8f/2/

pregmatch
  • 2,629
  • 6
  • 31
  • 68
  • Thanks pregmatch for this answer and for checking the other answer. I will study this logic to solve the problem. n_n – Rafael Nov 23 '16 at 17:44
1

You can achieve the desired using css3 like this on changeImage() function.

@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.container { top: 20%; left: 20%;}

.fade-in {

   animation:fadeIn ease-in 1;
   animation-duration:5s;
}
<script type="text/javascript">
function changeImage(a) {
  
  var elm = document.getElementById("Image");
  var clonedElm = elm.cloneNode(true);
  elm.parentNode.replaceChild(clonedElm, elm);
  document.getElementById("Image").src = a;
  
}
</script>

<div>
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/3/3c/Perkin_Warbeck.jpg/200px-Perkin_Warbeck.jpg');">
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg" onclick="changeImage('https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Leonard_Cohen_2008.jpg/200px-Leonard_Cohen_2008.jpg');">
</div>


<div class="container">
  <img id="Image" src="" class="fade-in">
</div>
Deep
  • 9,594
  • 2
  • 21
  • 33
  • Thanks for the answer. I can play a bit more with this, as the css is separated from the script. – Rafael Nov 23 '16 at 17:45