Search code examples
javascriptfor-loopjslint

Don't make functions within a loop error I can't fix


So I'm using JSlint and I'm trying to implement the following code, but I'm getting the error message "Don't make functions within a loop error I can't fix". Any idea how I can alter my code to make this not receive errors/warnings?

var inputs = document.getElementsByTagName('input');
var blurInput = function () {
    this.blur();
};
for (var i = 0; i < inputs.length; i++) {
    (function (input) {
        input.addEventListener('focus', blurInput);
    })(inputs[i]);
}

Solution

  • You'd want to move your function outside your loop:

    var inputs = document.getElementsByTagName('input');
    var blurInput = function () {
        this.blur();
    };
    
    // (rename this to something useful...)
    var doSomething = function (input) {
      input.addEventListener('focus', blurInput);
    };
    
    for (var i = 0; i < inputs.length; i++) {
        doSomething(inputs[i]);
    }