Search code examples
javascripthtmlimagesrc

see if src of img exists


when I place an img tag I create the src attribute dynamically. Is there a way of testing if the src (path where the image is located) actually exists with javascript in order to avoid getting:

enter image description here


Solution

  • You can use the error event:

    var im = document.getElementById('imageID'); // or select based on classes
    im.onerror = function(){
      // image not found or change src like this as default image:
    
       im.src = 'new path';
    };
    

    Inline Version:

    <img src="whatever" onError="this.src = 'new default path'" />
    

    Or

    <img src="whatever" onError="doSomething();" />
    

    <img> tag supports these events:

    • abort (onAbort)
    • error (onError)
    • load (onLoad)

    More Information: