10

I have content with broken images, multiple images in each page. Some images have empty src value and some just broken 404 links.

I have been trying to use

<script type="text/javascript">
$(document).ready(function () {
    $("img").error(function(){
    $(this).hide();
    });
}); 
</script>

It doesn't work as expected, doesn't work in IE, and in chrome I have to reload the page after first load to hide the images. Googled a lot, but all other codes are the same.

Editing the <img> tag is NOT an option for me.

What is wrong with that code?

D_Guy13
  • 491
  • 2
  • 5
  • 17

5 Answers5

21

Use it instead

<img src="image.png" onError="this.onerror = '';this.style.visibility='hidden';" />

test

or you can do it for all of your images

$(window).load(function() { 
   $("img").each(function(){ 
      var image = $(this); 
      if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){  
         $(image).unbind("error").hide();
      } 
   }); 
});

demo

Telvin Nguyen
  • 3,459
  • 4
  • 22
  • 38
  • I can't fix it that way, I'm getting the content from another domain with pre-populated tags. – D_Guy13 Jul 29 '13 at 18:10
  • Could you demo it on jsfiddle where I can see? I've tried on IE and chrome, it worked fine. http://jsfiddle.net/pnSen/6/ – Telvin Nguyen Jul 29 '13 at 18:28
  • With your code I have to edit 200 000 articles :) manualy. that is not an option for me. Thanks anyway. Hope someone can modify my code. – D_Guy13 Jul 29 '13 at 18:44
  • I see that it's working in your demo. But in my website it adds this to the missing image --> style="display: none; but still shows the broken image icon in browser. – D_Guy13 Jul 29 '13 at 20:03
  • `onError="this.onerror = '';this.style.display='none';" />` might be more desirable if the unloaded image has a set size and takes up space. This allows its presence to completely removed from the page. – GoodLuckClay Aug 12 '15 at 05:24
2

It is very simple,

You just have to add an onerror attribute:

<img src="image.png" onerror='$(this).hide();'/>

If the image gives an error it hides

PatrickH
  • 39
  • 6
2

Why not just combine DOM events with jQuery:

$("img").each(function () {
    var $this = $(this);

    this.onerror = function() {
        $this.hide();
    };
});

This worked for me.

Jordan
  • 8,881
  • 8
  • 63
  • 130
0

For images that might exist i find most elegant solution is useing $ajax, like:

$.ajax({
    url: 'your_image.jpg',
    type: "POST",
    dataType: "image",
    success: function() {
        /* function if image exists (setting it in div or smthg.)*/
    },
    error: function(){
       /* function if image doesn't exist like hideing div*/
    } 
});

But some people like useing hiden images that show themselves after load like:

<img src="your_image.jpg" onload="loadImage()">

Both solutions are efective, use one that suits your problem best

well if u can't edit img try something like:

$(document).ready(function () {
    $("#img").hide();
    $('#img').load(function() {
     $("#img").show();
    });
});

BTW do you have image id or do you need to do this for random amount of pictures whos id you don't have???

Ivan Pavić
  • 466
  • 4
  • 20
  • Number of images are random, and they are Not targeted by any class or ID. Some pages contain 1 image, some other contains more than one. – D_Guy13 Jul 29 '13 at 20:10
0

I was working on a something similar where I had to update my DOM using a JSON feed which consisted on image urls but before updating the DOM I had to detect broken images and also avoid loading images with width > 1000px. I tried adding inline onerror solutions and query DOM after loading the page and remove or hide the div before its displayed but it was costly and hindered user experience. I think this is a better approach and saves DOM query and can work on any browser.

Here is the solution on jsfiddle. http://jsfiddle.net/vchouhan/s8kvqj3e/60/

$(document).ready(function () {
// For demo purposes, I'm going to pass this URL variable to my function.
//resolved URL
var url = "http://asmarterplanet.com/mobile-enterprise/files/bus-stop-app.png",

//broken url
 brokenUrl = "http://pbs.twimg.com/profile_images/481800387230318592/pVyU2bzj_normal.jpeg";

    //Method takes the URL as a parameter to check if it resolves
var f_testImage = function(url){
    /*
        When the preloadImages Async call returns the object
        Validate and do the needful 
    */
    $.when(f_preloadImages(url)).done(function (returnedObj){
        /*
            If successful and Width > 500 
            (this was for my purpose, you can ignore it) 
        */
        if (returnedObj && returnedObj.width > 500) {
            alert("width greater than 500px: "+ returnedObj.width + "px"); // Alerts src.width > 500                 
        } else {
            alert("width smaller than 500px: "+ returnedObj.width + "px"); // Alerts src.width < 500               
        }
    }).fail(function(returnedObj){     // Fail condition captured through imgDfd.reject();      
        alert("image URL is broken and the width is: " + returnedObj);
    });
};

var f_preloadImages = function(imgurl) {
    var img = new Image(); // declare new img object
    imgDfd = new $.Deferred();// declare new deferred object

    // Test onload
    img.onload = function () {
        return imgDfd.resolve(img);
    };
    // Test onerror
    img.onerror = function () {
        return imgDfd.reject(0);
    };

    //Add imgURL to imgSrc after onload and onerror is fired
    img.src = imgurl;
    return imgDfd.promise();
};

//Fire testImage with url and then with brokenUrl as parameter
f_testImage(brokenUrl);

});

Vish
  • 335
  • 2
  • 8
  • 23