Search code examples
javascriptonloadappendchild

How to pass element to append image to in to the image.onload() function


I am writing a library that creates multiple elements inside a wrapper element, and stores all this and its functions inside a JavaScript object. I am trying to avoid IDs, as there might be multiple instances of this object on a page. I have a function to allow the user to change some of the elements, and I need help figuring out how to append an image.

Here is the function:

foo.prototype.rebrand = function(line1, line2, imgUrl){
    this.branding.childNodes[1].innerHTML = line1;
    this.branding.childNodes[2].innerHTML = line2;
    var brandImage = document.createElement('img');
    brandImage.onload = function(){
        this.branding.childNodes[0].appendChild(brandImage);
                    //this won't work
    }
    brandImage.src = imgUrl;
}

You would call foo.rebrand('hello', 'world', 'example.png')

Unfortunately, inside the .onload function, this will refer to the image element itself. So, how can I pass this.branding.childNodes[0] in to the image onload?

If I write the function like so:

            brandImage.onload = function(anything){
        this.branding.childNodes[0].appendChild(brandImage);
                    //this won't work
    }

then anything will just be a reference to the onload event.

Edit to add jsFiddle: http://jsfiddle.net/KtJd6/


Solution

  • You need to change the way you are referencing specific elements to retrieve elements, not childNodes. This will make it a lot more robust. And, when you do that, you won't need the reference this in the onload handler either.

    foo.prototype.rebrand = function(line1, line2, imgUrl){
        var brandImage = document.createElement('img');
    
        // find child divs
        var divs = this.branding.getElementsByTagName("div");
        divs[0].innerHTML = line1;
        divs[1].innerHTML = line2;
    
        brandImage.onload = function(){
            divs[0].appendChild(brandImage);
        };
        brandImage.src = imgUrl;
    };
    

    Note, that I'm getting elements with getElementsByTagName() and NOT referring to direct childNode indexes. This makes it insensitive to where text nodes are and is a lot more robust way of referring to elements you want to target and modify.

    You can see it work here: http://jsfiddle.net/jfriend00/kkXCg/