title: Unexpected behaviour when previewing images before uploading
body: <p>I have been working on previewing multiple images before they are uploaded and tried using @ratan-paul response to the <a href="https://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded">"Preview an image before it is uploaded"</a> quite useful. However when I tried to tweak the code a bit I got a rather unexpected result. What I did was to create a <code>&lt;span&gt;</code> tag for each <code>&lt;image&gt;</code> to add some styling options. Here's the jQuery code I ended up with:</p>
  
  <pre><code>$(function () {
      var span_id = "";
      function readURL(input) {
          for(var i =0; i&lt; input.files.length; i++){
              var span = $('&lt;span&gt;');
              span_id = "span"+i;
              span.attr('id',span_id);
              span.appendTo('#img-previews');
              if (input.files[i]) {
                  var reader = new FileReader();
                  reader.onload = function (e) {
                      var img = $('&lt;img id="dynamic"&gt;');
                      img.attr('src', e.target.result);
                      img.attr('height','150px');
                      img.attr('width','200px');
                      img.appendTo("#"+span_id);
                  };
                  reader.readAsDataURL(input.files[i]);
              }
          }
      }
  
      $("#imgUpload").change(function(){
          readURL(this);
      });
  });
  </code></pre>
  
  <p>Now the strange thing is that when I run the code above I create a <code>&lt;span&gt;</code> tag for each image but all the images get crammed into the last <code>&lt;span&gt;</code> created. On the other hand if i debug the script I get the wanted result where each image is inserted into its own <code>&lt;span&gt;</code> tag. I'm kinda baffled by this so if anyone has any ideas as to why this is happening or how to avoid it would appreciate the assistance.</p>
  
  <p>Here is a screen grab of when I run the script without debugging:
  <a href="https://i.stack.imgur.com/v9grk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v9grk.png" alt="Screen grab of unexpected behavior"></a></p>
  
  <p>And here is a screen grab of the result when stepped through with the js debugger
  <a href="https://i.stack.imgur.com/hspQB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hspQB.png" alt="Result when stepping through a JS debugger"></a></p>