Hide broken images jQuery
Asked Answered
A

5

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?

Akins answered 29/7, 2013 at 17:53 Comment(2)
Here is fast & Quick way #93220Planchette
Here is fast way to do it #93220Planchette
M
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

Myocarditis answered 29/7, 2013 at 18:7 Comment(5)
I can't fix it that way, I'm getting the content from another domain with pre-populated tags.Akins
Could you demo it on jsfiddle where I can see? I've tried on IE and chrome, it worked fine. jsfiddle.net/pnSen/6Myocarditis
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.Akins
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.Akins
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.Gilud
S
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

Serrated answered 16/10, 2013 at 14:52 Comment(0)
C
2

Why not just combine DOM events with jQuery:

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

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

This worked for me.

Chicalote answered 9/2, 2015 at 16:4 Comment(0)
A
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???

Anglian answered 29/7, 2013 at 18:53 Comment(1)
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.Akins
T
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);

});

Tweed answered 19/9, 2014 at 18:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.