Search code examples
javascripthtmlimageonerror

HTML: trigger onerror twice to display the alternate of the alternate image


I'm in a situation where I know the name of an image, but not the exact extension. The extension could be .jpg or .png. Furthermore, the image itself might not even exist. So I have to perform the following:

  1. Attempt to load image.jpg
  2. Onerror, attempt to load image.png
  3. Onerror, display notfound.jpg

I've written the following code:

<img src=image.jpg onerror="this.onerror=null; this.src=image.png;">

But "this.onerror=null" only stops onerror from going into infinite loop. How can I load the alternate of the alternative image, "notfound.jpg", when onerror is triggered again?


Solution

  • Here I have what i would do using jquery. I asked you if i could and you didn't reply.

    So here it is.

    Here would be the standard html:

    <img src=image.jpg alt="" />
    

    here would be the jquery attached to it:

    $('img').on('error', function () {
        var $this = $(this);
        // ajax with type 'HEAD' checks to see if the file exists
        $.ajax({
            url: 'image.png', //place alternate img link here
            type: 'HEAD',
            success: function () {
                //if success place alternate image url into image
                $this.prop('src', 'image.png');
            },
            error: function () {
                //if error place notfound image url into image
                $this.prop('src', 'notfound.jpg');
            }
        });
    });
    

    Here i have it working in a different environment but it shows the end product: http://jsfiddle.net/6nFdr/