1

I'm using this code:

function init(){
        var s = document.getElementsByClassName("seen");
        for(var i = 0; i < s.length; i++) tint(image_seen, 93, 196, 82, 255, function(d){
            s[i].src = d;
        });
    }

to set data urls for images with a classname. The function tint() does not return a value since to tint an image, it should be drawn to canvas (using callbacks). However, I get an error stating it cannot set src property of undefined. console.log(i) always returns 1. (there is a total of 1 img.seen elements).

This drives me insane. What's wrong?

user7401478
  • 1,372
  • 1
  • 8
  • 25
  • 1
    search, this is probably the #1 question about JS's for-loops – dandavis Feb 01 '17 at 21:27
  • your all the functions refer to the same variable, and at the end of `for` loop this variable is equal to `s.length`. use closures to handle this. Look here for details - http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Telman Feb 01 '17 at 21:37

0 Answers0