title: Adding event listeners on array of pics in specific way
body: <p>I have a bunch of images, that should be distributed in container one by one, which means <strong>each image shows exact after previous image is loaded and showed</strong>, and each image should get an event listener.<br>
  Here is my solution <a href="https://jsfiddle.net/e2sfzn1u/4/" rel="nofollow noreferrer">https://jsfiddle.net/e2sfzn1u/4/</a> <br>
  I have used <code>Image.onload</code> to add the image node to the markup and to define event listener for that node, and when these are ready, it goes to another image (recursively).</p>
  
  <pre><code>var pics = [
     'http://i.imgur.com/1oT2ZpOb.jpg',
     'http://i.imgur.com/XsViuLib.jpg',
     'http://i.imgur.com/aTDTI8Eb.jpg',
     'http://i.imgur.com/4kLvWOdb.jpg'
  ]
  var cont = document.getElementById('container');
  var each = function(arr, i) {
     if (i === undefined) {
        i = 0;
     }
     if (i &lt; arr.length) {
        var img = new Image();
        img.onload = function() {
           cont.innerHTML += '&lt;div class="sas" id="' + i + '" &gt;&lt;/div&gt;';
           var pic = document.getElementById(i);
           pic.appendChild(img);
           pic.addEventListener('click', function() {
              alert('mda')
           });
           each(arr, i + 1);
        };
        img.src = arr[i];
     }
  };
  each(pics);
  </code></pre>
  
  <p>Looks simple, but there is a problem - event listener is defined only for last element. </p>