Using JavaScript, how can I replace broken images with any other HTML data

I provide a service that helps users find the location of images. My problem is that the photos are stored on another internal site and my users must be connected to it to see the photos (some may not have access as my service provides different information). Inline replacement (the alt attribute of the IMG) does not provide enough flexibility to inform the user of corrective action.

<div id=theDiv>
    <img src='http\internalSite\'+this.name+'.jpg'
    alt='Please connect to internalSite to see the picture '+this.name+'.jpg'>
</div>

      

I would like to improve the alt text, at least provide a link to "internalSite" (or better yet, load the connection page in an iFrame, maybe ...). I found this impossible, so I would use the onError IMG attribute to replace what I have on the div

But actually the image is being placed here by the script, so I think this is a bit silly and clearly not optimized how my script detects that the picture is not available before to decide what I am doing?

in pseudocode:

if (isURLavailble(path)){
    loadPicture();
} else {
    loadSomethingNiceToSayPicIsntAvailable() ;
}

      

it is possible to define a working function (and of course cross-browser) that makes isURLavailble (path);

+3


source to share


2 answers


You can replace all broken images (or a subset of them) with login links:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Test</title>
    </head>

    <body>

        <img src="doesnotexist">

        <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
        <script>
            // See also /questions/13278/check-if-an-image-is-loaded-no-errors-in-javascript/95237#95237
            $( document ).ready( function () {
                "use strict";
                $('<a href="login">login here</a>').replaceAll($('img').filter( function () {
                    return !(this.complete && this.naturalHeight !== 0);
                }));
            });
        </script>

    </body>
</html>

      

See also this answer on Check if image loaded (no errors) in JavaScript .



Or you can do something like this if you set images after the page has loaded:

var img = new Image();
img.onload = function () {
    $(img).appendTo('.image-container');
};
img.onerror = function () {
   $('<a href="login">login here</a>').appendTo('.image-container');
};
img.src = 'doesnotexist';

      

+2


source


You can check the url using jQuery jqXHR calls:



$.get("urlToCheck.com").done(function () {
  loadPicture();
}).fail(function () {
   loadSomethingNiceToSayPicIsntAvailable() ;
});

      

+2


source







All Articles