Question

Eventually, I want the user to be able to click the node, be presented with a choice of images and fill the node with their choice. For now, however, I am just trying to test how to change the image placed in the node on table creation with a different image onclick. Is my logic fuzzy?

for (r = 0; r < howOften; r++) {
        row = table.insertRow(-1);

        for (c = 0; c < numDays; c++) {
            col = row.insertCell(-1);
            img=new Image();
            img.src="../www/images/TEST.png";
            col.appendChild(img);

                img.onclick = function() {
                image1= new Image();
                image1.src="../www/images/TEST2.png";
                img=image1;     
                };
            }
        };
    document.getElementById('holdTable').appendChild(table);
};
Was it helpful?

Solution

When you append img to col, you append the image that is "pointed to" by the variable img. If (when) you later change the variable img to point to another value, it does not change what was appended to col. You can test it by adding img = 'hello'; right after you appendChild it - you will find the img is appended and not 'hello'.

In the onclick function When you change img to "point to" image1, it does not change the image that was appended to col.

If you want to truly change what was appended to the dom you need to remove the Image and insert another object in its place.

But luckily what you want is an image with another src, so you don't need to remove the image from the dom and insert another - you just need to change the src of the image that is already there. To do that what you should do is use the "this" variable (which points to the image that is in col) in the onclick function and change its "src".

ie.

img.onclick = function() {
    // wrong:
    //var image1= new Image();
    //image1.src="../www/images/TEST2.png";
    //img=image1;  

    // right:    
    this.src = '../www/images/TEST2.png';
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top