user1531921
user1531921

Reputation: 1432

How to detect if image URL doesn't work

I got a javascript problem. I'm building a website which communicates with a MovieDB-API which will sometimes return broken URLs.

This screenshot pretty much explains it

Is there any way to detect whether the URL returned by the API is going to lead to an empty page? Perhaps by checking retroactively if the image defaulted to the "alt"-attribute? Obviously, since the alt-text is showing, the program is "aware" of the fact that the URL fails.

In case the URL is broken, I want to have the IMG-variable replaced by the path to a local default-image.

Upvotes: 0

Views: 1757

Answers (3)

4dgaurav
4dgaurav

Reputation: 11506

CSS with javascript enabled

<img src="image.jpg" onerror="this.src='alternative.jpg';">

OR

jquery

// Replace source
$('img').error(function(){
        $(this).attr('src', 'missing.png');
});

// Or, hide them
$("img").error(function(){
        $(this).hide();
});


Edit

$(document).ready(function () {
    $('img').error(function () {
        $(this).addClass('noImg');
    });
});

.noImg {
  position: relative;
  background: url() no-repeat center center; // or simple background color
  height: 100px;
  width: 100px;
  content: "Your content";
  margin: 0 10px 10px 0;
}

Upvotes: 3

gyss
gyss

Reputation: 1843

You could try to do an Ajax request for every image. If it does exist it will return success. Otherwise it throw an error and you can put the desired image in this place. jQuery Ajax snippet:

$.ajax({
    type: "GET",
    url: url_to_img,
    success: function(result) {
        console.log("SUCCESS");
        $('#img-1234').attr('src', url);
    },
    error: function(result) {
        console.log("ERROR");
        // url broken
        $('#img-1234').attr('src', '/img/noImg.png');
    }
});     

Hope it helps

Upvotes: 1

adeneo
adeneo

Reputation: 318192

You can use the onerror event to check the URL and see if the image can be loaded.

var url = 'http://www.somesite.com/image.jpg';

var img = new Image();

img.onerror = function() {
    console.log('image could not be loaded, setting default placeholder');
    image_tag.src = '/my_default_placeholder.gif';
}

img.src = url;

without any posted code, it's just a general example of how it would work,

Upvotes: 2

Related Questions