Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top