0

I want to make all images in my website have "Fadein" effect when loading finished , so What is the problem with this code ? !

<img 
src="http://1.bp.blogspot.com/-M03SoTLlJ4k/Vfwvq2dz42I/AAAAAAAAD9I/o-xN8x6HL2Y/s1600-r/Untitled-1%2B%25281%2529.png"  id="image_id"/>
<style>
#image_id { 
opacity:0; 
transition:1s;
}
</style> 
<script>
var i;
var x = document.getElementsByTagName("img");
for (i = 0; i < x.length; i++) {
    document.getElementsByTagName("img")[i].addEventListener("load", imgfadein);
    };
function imgfadein() {
 x[i].style.opacity = "1";          
}
</script> 
peter hany
  • 43
  • 1
  • 9
  • 2
    Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Sebastian Simon Aug 16 '16 at 17:20

1 Answers1

2

In your code, when the event handler runs, i is x.length, so x[i] is not set.

When the event listener function runs, this is the element that it was bound to. Use this instead of x[i].

function imgfacein() {
    this.style.opacity = "1";
}
Barmar
  • 741,623
  • 53
  • 500
  • 612