Tomihar
Tomihar

Reputation: 23

Loading images with loop to <img> tags

I have following code:

$("input[type=file]").change(function readURL()
{
   if (this.files)
   {
      var num = this.files.length;    
      for(var i = 0; i < num ; i++)
      {
         var file = this.files[i];
         var reader = new FileReader();
         reader.onload = function(qi)
         {
            return function()
            {
            $("#img"+(i)).attr('src',event.target.result);
            };
         }(i);
         reader.readAsDataURL(file);
      }
   }
});

And some HTML

<img id="img1" class="img-thumbnail thumnbail">
<img id="img2" class="img-thumbnail thumnbail">
<img id="img3" class="img-thumbnail thumnbail">
<img id="img4" class="img-thumbnail thumnbail">
<img id="img5" class="img-thumbnail thumnbail">
...

What I'm trying to do is to load all images as a thumbnails to tags, but only last is being loaded. Adding console.log(i) to return function showed me that this function returns last value of i i times. What I should do to make it work?

Upvotes: 1

Views: 123

Answers (1)

MrCode
MrCode

Reputation: 64526

You have correctly created a closure, which is the right thing to do, but you are still referencing the i variable from the upper scope, not qi from the closure.

Change this:

$("#img"+(i)).attr('src',event.target.result);

To:

$("#img"+(qi)).attr('src',event.target.result);
//        ^^ use qi here

Upvotes: 4

Related Questions