Q:

Using closures in onerror attribute does not seem to work

I have this piece of code in a rather large JS file.
function accError() {
  console.log("hello there");
}

var setAccount = function(key) {
  var error = function() {
    accError();
  };
  document.body.innerHTML += "<img src='//www.somerandomdomain.in/i.jpg?key=" + key + "' onerror='error();' />"
};

setAccount("a");

If the image load fails I want to call the error function. But it gives me an error - error is not defined. 
JSFiddle here = http://jsfiddle.net/rrvvw1sj/
How does scoping work in the case of load or error callbacks for images or any other element? Shouldn't error() function be accessible using closures?

A:

The reason that your img tag can't find the error function is that it has no access to the closure's scope.
document.body.innerHTML += "<img src='//www.somerandomdomain.in/i.jpg?key=" + key + "' onerror='error();' />"

This line of code does not send anything to the document that can link back to the closure. 
What it sends is a string.
The string is then parsed in the scope of the document.  Since your error function doesn't exist in the global scope it won't be found. 
What you need to do is create an object inside your closure and attach the error function to it.  Then if you send that object to the document it will maintain its connection to the error function inside your closure.  You can do this by using DOM (Document Object Model) methods to create an img element node and then append that object to the body.  Then you have a reference in the closure to the element and can use addEventListener to attach the error function to the error event
//document.body.innerHTML += "<img src='//www.somerandomdomain.in/i.jpg?key=" + key + "' onerror='error();' />"

var img=document.createElement("img");
img.setAttribute('src', '//www.somerandomdomain.in/i.jpg?key=' + key);
img.addEventListener("error", error);
document.body.appendChild(img);

