Question

So I'm writing a javascript that replaces a default image that fills up the space for numerous images on my webpage. That way, the page loads much faster. (script is lauched with a body onload) all the default images have the same class and their id equals their filename.

function imgPostLoad(totalpics, placeholder) {
    var img = document.createElement('img');
    for (var i = 0; i < totalpics; i++) {
        var picture = document.getElementsByClassName(placeholder)[i];
        img.onload = function (evt) {
            picture.src = this.src;
            picture.width = this.width;
            picture.height = this.height;
        }
        img.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}

It works but only for the very last last image in the array. The rest of the images just stay the same. What's wrong with it?

Was it helpful?

Solution

You could just simply do :

function imgPostLoad(totalpics, placeholder) {
    for (var i = 0; i < totalpics; i++) {
        var picture = document.getElementsByClassName(placeholder)[i];
        picture.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}

What the problem is in your code is that by the time img was loaded picture is another variable.

OTHER TIPS

function imgPostLoad(placeholder) {
    var allPictures = document.getElementsByClassName(placeholder);
    for (var i = 0; i < allPictures.length; i++) {
        var picture = allPictures[i];
        picture.src = "/img/" + picture.getAttribute("id") + ".jpg";
    }
}

Actually, it would be cleaner to write it like this.

function imgPostLoad() {

     var placeHolders = document.body.querySelectorAll('.placeholder');

    for (var i = 0; i < placeHolders.length; i++) {

        placeHolders[i].src = "/img/" + placeHolders[i].getAttribute("id") + ".jpg";
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top