NAME__
NAME__

Reputation: 633

jQuery Image load error not being called after page load

Hello Stack Overflow community, recently, I've been working on a quick image display using jQuery. It has a list of possible images that can be picked and displayed at random. The issue is, after the page has finished loading, jQuery ceases to detect image load errors for if the image is invalid.

My current method of finding and fixing errors is as follows:

$('img').error(function() {
    $(this).attr('src',getImgUrl());
});

This, in normal circumstances such as the page being loaded, picks a valid image, even if multiple invalid images are specified in a row. However, after the page is finished loading, if an invalid image is picked, and fails to load, this function is not even called. Strangely enough though, if I add an onerror attribute to all images, they are always called from the onerror no matter if the page was freshly loaded or not, so why is jQuery having this issue? Any help is appreciated, thanks.

UPDATE: It also appears this is happening to other jQuery functions as well, such as click.

UPDATE: It would appear to be an issue with jQuery recognizing new elements on a page, such as newly created images.

UPDATE for those asking getImageUrl:

function getImgUrl()
{
    var text = (Math.round(Math.random() * 3)).toString();
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for(var i=0; i < 4; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return '/' + text;
}

All this does is pick a random URL, which matches occasionally to an image on my web-server that has many many images.

Upvotes: 0

Views: 395

Answers (1)

NAME__
NAME__

Reputation: 633

It would appear that jQuery has issues recognizing new elements on the page, so the way I fixed this was instead of deleting and adding images to the page, I just edited the existing SRC of images when doing changes, which strangely enough, the jQuery error function responds perfectly to.

Here's the refresh function I ended up coming up with for all interested:

function refreshImages()
{
var images = 10;

for(var i = 0;i < images;i++)
{
    var url = getImgUrl();

    $('#thumb' + i).attr('src',url);

    if(i == 0)
    {
        $('#fullimage').attr('src',url);
        $('.thumb').css('border','2px solid white');
    }
}
resize();
}

Upvotes: 1

Related Questions