0

I'm trying to replace the background of an array of elements when the larger images are loaded (custom lazy loading?). I successfully managed to make it work with only one element, however when I tried to make it to iterate on all elements I ran into a few issues.

I think I'm doing something wrong with the for loop or the onload fuction inside it.

Here is my current code:

var cards = document.querySelectorAll('.card');

var currentCard;

if (document.images) {

    var imgs= [img1 = new Image(), img2 = new Image(), img3 = new Image()];

    for (var i = 0; i < imgs.length; i++) {

        currentCard = cards[i];

        console.log(currentCard);

        imgs[i].onload = function() {

            console.log(currentCard);

            currentCard.style.backgroundImage = "url(" + this.src + ")";
        };
    };

    img1.src = "/346954/97bd0a99b786df85fa0e80156e67c450.jpg";
    img2.src = "/346954/29578.jpg";
    img3.src = "/346954/500759045.jpg";
};

My first console log returns exactly what I want, three different elements: card-1, card-2 and card-3.

However the one inside the onload function always returns the same one three time: card-3. it looks like the "currentCard" value is always the same inside the onload function even though the value is updated every iteration.

It must be something pretty simple but I'm not seeing it. If someone can help me it will be really appreciated.

JimyPP
  • 105
  • 3

1 Answers1

0
currentCard.style.backgroundImage = "url('" + this.src + "')"
hashbytes
  • 769
  • 1
  • 8
  • 26
  • I just mistyped the code here on StackOverflow. That is unfortunately not the issue. I've update the question with the correct code. – JimyPP Apr 08 '18 at 16:19
  • The issue seems to come from the fact that it only replaces the background on one card, as if the "currentCard" had always the same value. – JimyPP Apr 08 '18 at 16:20