javascriptjqueryimagedomonerror

Loading an image but onload/onerror not working as expected


I have a div

<div id='cards'>

Which I want to fill with images based on some logic. But only when images are first loaded into memory. Otherwise, through onerror I wanna fill in some text..

function pasteCard(card, to){
    if (typeof(card) == 'string')
        card = [card];
    var image = [];
    for (var i = 0; i < card.length; i++) {
        image[i] = new Image();
        image[i].src = '/sprites/open/' + card[i] + '.png';
        image[i].onload = function() {
            pasteImage(to, image[i]);
        }
        image[i].onerror = function() {            
            pasteText(to, card[i]);
            
        }
        // alert(card[i]) #1
    }

    function pasteImage(to, image) {
        to.append(image);
    }

    function pasteText(to, text) {
        // alert(card[i]) #2
        to.append(text);
    }    
}

pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));

But this isn't working.

Problem/weirdness: If only #2 alert is active it returns nothing. But strangely if #1 alert is also active it does kinda work... (but still doesn't load my images, and mostly fails too when other code is involved)

Question: Why is it not working without #1 alert (at least in that jsfiddle)

suggestions?: what should I do?


Solution

  • Onload and onerror events are fired (executed) outside the scope of your function so your variables will be undefined. In the event method you have access to this which is the image object. You can set a data attribute to each image and access that in your error event.

    Here is an example: http://jsfiddle.net/7CfEu/4/