user2898075
user2898075

Reputation: 79

Detect 404 with javascript

I'm currently using this JavaScript function to load an image into a div.

function loadImage(id) {
    var image = document.getElementById("image");
    image.src = "http://test.com/"+id+".png";
    var image = document.getElementById("image");
    image.onload = function () {
            // Do stuff
    };
}

However, how can I do something if the image URL throws back a 404 error?

Upvotes: 1

Views: 7227

Answers (1)

v6ak
v6ak

Reputation: 1656

You can use onerror.

I am not sure if it reacts also on images as a 404 page, or on bad images only. In both cases, it will likely do what you need.

Alternatively, you can try using AJAX (e.g. XMLHttpRequest or its abstraction), which allows you to handle error codes. Cross-origin restrictions will apply, though. It may be also an overkill.

Upvotes: 4

Related Questions