Search code examples
javascriptimageerror-handlingonloadsrc

Is there code that can be used to alert user when image does not load?


I have an image that I am loading from a server. I am doing this through the following code.

img.onload = function () {
   loadingStop = true;
   ctx.drawImage(img, 10, 10);
   startDrawing();
}
img.src = imageLink;

When the image loads the program goes on its merry way. However, incase the photo will not load, I want to alert(msg) the user of the problem. How can I do this with JavaScript?


Solution

  • Just use onerror

    <img src="../missing-file.jpg" onerror="myAlertFunction()">
    
    function myAlertFunction() {
      alert('The image could not be loaded.');
    }