title: Filereader: Multiple file input ends with only one image as preview
body: <p>Trying to figure out how to input multiple files at once and arrange them to divs. In result, only the last image of the array appears.</p>
  
  <p><strong>HTML:</strong></p>
  
  <pre><code>&lt;input type="file" id="imageinput" accept="image/*" onchange="handleFiles(files)" multiple&gt;
      &lt;div class="cube-layout-1"&gt;
          &lt;div id="preview1"&gt;&lt;/div&gt;
          &lt;div id="preview2"&gt;&lt;/div&gt;
          &lt;div id="preview3"&gt;&lt;/div&gt;
          &lt;div id="preview4"&gt;&lt;/div&gt;
          &lt;div id="preview5"&gt;&lt;/div&gt;
          &lt;div id="preview6"&gt;&lt;/div&gt;
      &lt;/div&gt;
  </code></pre>
  
  <p><strong>Javascript:</strong></p>
  
  <pre><code>        var j=0;
  
          function counter() {
              j++;
              return j;
          }
  
          function handleFiles(files) {
              for (var i = 0; i &lt; files.length; i++) {
                  var file = files[i];
                  var count = counter();
                  var preview = document.getElementById("preview"+count);
  
                  var reader = new FileReader();
                  reader.onload =  (function (preview) {
                      return function () {
                          preview.style.backgroundImage = "url(" + reader.result + ")";
                      }
                  })(preview);
                  reader.readAsDataURL(file);
              }
          }
  </code></pre>
  
  <p>For example, if I choose 3 images at once, the first two divs get an empty background image and only the last div gets the image.
  I know it has something to do with the reader.onload event, which triggers only when the loop ends....but how can I achieve what I am aiming for? Thanks in advance!</p>