Rafael Rafael - 15 days ago 7
CSS Question

Add a fade in on images loaded by JavaScript

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?

Answer

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>