0

I have an issue by adding images to a div with .appendTo while I'm in a for-loop and in the .bind("load")-handler. I tried so many things but nothing worked, it only shows the last picture and not the three. The code is pretty simple as shown below.

If anyone has a hint for me, this would be great. Thanks in Advance!

var $images = ["https://static.pexels.com/photos/769986/pexels-photo-769986.jpeg", "https://static.pexels.com/photos/767907/pexels-photo-767907.jpeg", "https://static.pexels.com/photos/746759/pexels-photo-746759.png"];

var i,
  figure,
  img;

for (i = 0; i < $images.length; i += 1) {

  figure = $('<figure />');
  img = $('<img />');

  img.attr("src", $images[i]);

  img.unbind("load");
  img.bind("load", function() {

    a = $('<a>', {
      href: this.src,
      itemprop: "contentUrl",
      'data-size': this.width + "x" + this.height
    });

    img.appendTo(a);
    a.appendTo(figure);
    figure.appendTo('#gallery-panel');
  });
}
img {
  width: 10em;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>

<body>
  <div id="gallery-panel"></div>
</body>

</html>
J. Cole
  • 47
  • 6

1 Answers1

0

Change:

img.appendTo(a);

to:

$(this).appendTo(a);

You're running into the Javascript infamous Loop issue? because all the closures are using the same img variable.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thank you! This saved my life sat hours in front of this issue tried to do all crazy stuff with .append, .innerHTML, ... – J. Cole Jan 04 '18 at 22:59