Why the onclick manipulation function does not work as expected?


I have the following little piece of code:

var instance = this;
window.onload = function () {
    for (var i = 0; i < array.length; ++i) {
        var currentDivId= array[i];
        var currentDiv = document.getElementById(currentDivId);

        try {
            if (!currentDiv) {
                throw 'Div id not found: ' + currentDivId;
            var image = document.createElement('img');
            image.src = 'img.jpg';
            image.onclick = function() {

        catch(e) {

This code is passed an array of id of divs. What it does is that, it renders an image at each of those divs and set their onclick property.

Say I have an array of strings: ['abc', 'xyz']

I want the code to place an image inside <div id="abc"></div> and another image inside <div id="xyz"></div>.

When you click the first image, instance.doSomething function should be called with parameter 'abc' and vice versa.

But the code does not work as expected. It always calls instance.doSomething with the last parameter in the array, in this case, 'xyz'.

I'm new to JS and still don't have a solid grasp of its inner workings. What's wrong here and how can I fix it?

Any help appreciated. Thanks.

image.onclick = function() {

That should do it. Since we know that the image is inside the div we want to get at, just go one dom element up and get its id.