Missing images will either just display nothing, or display a [ ? ] style box when their source cannot be found. Instead, you may want to replace that with a “missing image” graphic that you are sure exists so there is better visual feedback that something is wrong. Or, you might want to hide it entirely. This is possible because images that a browser can’t find fire off an “error” JavaScript event we can watch for.
// Replace source
$('img').on("error", function() {
$(this).attr('src', '/images/missing.png');
});
// Or, hide them
$("img").on("error", function() {
$(this).hide();
});
Additionally, you may wish to trigger some kind of Ajax action to send an email to a site admin when this occurs.
While this is neat and I didn’t know that imgs threw an error if they can’t be loaded, the usefulness of such a block seems low and somewhat heavy (attaching an event-listener to every img on a page) for something that shouldn’t occur very often.
I could see this being useful in a case where UGC is being created and the user uploads an image, you could try to display the image if its been processed by the server and if not show a placeholder.
In my experience, Chrome and Firefox recognise when images aren’t loaded and log it to the console, not sure about other browsers.
Hi,
This is chandru from Chennai(india)…
You hava a amazing site Every works is useful for me,
keep it up dude…
I really want to implement this on my site, but some of the images are rendered via a PHP script, and this bit of code hides those images for some reason. Can anyone help me out? I don’t like that ugly little icon showing up. I have a image sitting behind where the rendered image should be in case it cannot render it because it is trying to pull down a Minecraft skin and if a user did not upload one the default is not rendered.
Oops, never mind. Works now. Just played around a bit and got it.
Wish you would have provided your solution as I’m having the same problem.
Saddly, this does not work in IE – even through IE 9.
Great!! solved my error :)
no it did not on the second glance :((
I am getting missing image icons on my menu hover how can i deal with it??
It doesn’t work for background images.
You’ll have to add some to the script if this is your case.
in chrome (forgot to mention)
Hi all, i cant seem to get this to work. What should the code look like and do i place it before the head or the cose of the body
I was doing something similar to this, but then I found this is a bad choice.
Broken images are not always caused by invalid url or file-not-exist, it could be caused by temporary network problem or slow connection.
By changing image src of a broken image, users won’t get a chance to see what the real scr is (right click – view image info). It’s even worse to hide the broken image because it’s totally invisible.
So my solution is to leave the browser broken image alone, and add a reload-image click event to the image.
For some browsers, you might need to specify dimensions and a border
.broken-image {width: 16px !important; height: 16px !important; border: 1px solid #aaa;}
, otherwise the image will be invisible. And remove the class on image load.I don’t have any idea where to paste this code,
Can you please show me more detail?
It’s Actually on Your CSS Stylesheet, But i think Posting this is totally a bad idea.
Why not try putting background-image: url(whatever_image_name_is.jpg);.
If you don’t need a blank space so if image does not properly load the background-image would be there, rather than hiding or replacing image using Jquery.
A developer would totally understand what i mean.
I’m Precious Tom From Nigeria…
$(document).ready(function() {
$(“img”).error(function() {
$(this).hide();
});
});
…and then it waits for the site to load entirely and hides imgs afterwards.
Might cause flickering but surely hides all that needs to be hidden.
Hi Sakknekedro,
Great solution, however that flickering you are noticing can easily be avoided by not waiting for the document to be ‘ready’ before hiding the images.
Alright, why doesn’t it render markdown codeblocks?
This was just was I didn’t know I needed! I did how ever change a bit of it…. This way the original source would still be visible and right-click should work.
JS:
CSS:
noImg {
position: relative;
border: 1px solid lightgrey;
background-image: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg);
background-position: 50% 50%;
background-repeat: no-repeat;
-moz-background-size: contain;
-o-background-size: contain;
-webkit-background-size: contain;
background-size: contain;
height: 75px;
width: 126px;
content: "";
margin: 0 10px 10px 0;
}
shorthand
.noImg {
position: relative;
border: 1px solid lightgrey;
background: url(http://sirsyedcollege.org/wp-content/themes/EducationAcademy/images/no-image_980x516.jpg) 50% 50%/contain no-repeat;
height: 75px;
width: 126px;
content: "";
margin: 0 10px 10px 0;}
PS!
Image credit where image is stolen from, please replace with your own :)
Forgot to give credit to
Sakknekedro
In Safari 6.0.5, if you don’t use a background image but just a background color,
width
andheight
don’t have any effect if usingcontent: ""
. Sincecontent: ""
is the key factor here to hide both the?
icon and the inner white outline, this works if you just want a custom sized background placeholder:I went crazy trying to disable this white outline on a broken image, when my Last.fm script didn’t find an album cover so, glad I found this post.
I believe error is deprecated? Wont work in jQuery above 1.8?
These days (as of jQuery 1.7 I think) you’d want to do something like:
Doing this will attach one event listener to the document for img child elements, as opposed to the original way which attached a listener to every image element.
This doesn’t work unfortunately, as the browser doesn’t bubble up errors.
http://stackoverflow.com/a/18683695/18706
Funny solution to all AngularJS users..
WidgetApp.directive(‘img’, function(){
return {
restrict:’E’,
link:function(scope,element){
element.error(function(){
$(this).hide();
})
}
}
});
Sorry about that – clicked “send” before I checked it redners ok.
Nice little fix. But how do you prevent the flickering?
I’m using it to show a default image for a user if they have not uploaded one (no image data in their image location).
This worked for me, thanks! But I also had to put this code on the image to work:
Guy Mograbi, thanks for the angular code!
Might work for images that aren’t found, but what about blocked images? I’ve noticed if for some reason an image is blocked (i.e, mixed SSL content), this doesn’t really work – only worked in firefox. In order to get it to work, I had the function fire after the page loads, on a 10 millisecond time out; occasionally causes a flicker, but handles all broken images quite well.
My code:
Works in all browsers.
lotssss ……….. thanks bro u solve this big problem
thanks Eitz it’s work for me !
Do note that the error event is not triggered in Firefox if the src is empty. In that case, it will still render the missing image placeholder.
Please don’t use Eitz suggestion.
What about hiding the errors from the Console?
For me it was not working when it loads first, it is working only when I refreshed the page. But it starts working when I made the following changes,
$(window).load(function () {
$(‘img’).each(function () {
if (!this.complete || typeof this.naturalWidth == “undefined” || this.naturalWidth == 0) {
// if image was broken, replace with new image
this.src = ‘/Images/no_picture.gif’;
}
});
});
Do note that the error event is not triggered in Firefox if the src is empty. In that case, it will still render the missing image placeholder.
Please don’t use Eitz suggestion.
Very useful, thank you!
Also you can use .htaccess rewrites for missing files to other assets like suggested here.
If you use some specific folder structure you can serve also specific replacements for a specific path, ex:
Also, I’ve added a response header with the redirect of 307 for SEO, is it correct ?
Yes Sr! This is the only solution that worked for me. +1
These solutions are great but might I add a small change to the first example. I would change:
to this:
If for any reason the missing.png file can not be found, the browser will get stuck in an infinite error handling event loop. To avoid this, set the event to run only once and then unbind.
This works only for elements and if the script executes before the image error is thrown. That’s not an entirely reliable proposition unless you make sure to load your scrip synchronously before your images.
From http://stackoverflow.com/questions/1977871/check-if-an-image-is-loaded-no-errors-in-javascript#1978021:
Another option is to trigger the onload and/or onerror events by creating an in memory image element and setting its src attribute to the original src attribute of the original image. Here’s an example of what I mean:
If you end up here, know that the onerror function for images is deprecated. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#Browser_compatibility
how about this situation:
<img src="/fail-source-image.jpg" onerror="/fail-fallback-source-image.jpg">
both of image are fail for loading. It’s some how do the looping load because “onerror” is alway there? Saying, both of images are “*.webp” and you’re using safari.
What you guys thing about below code, i knew there’s something wrong with it but still … i can’t find it.
thank you.
<img src="/fail-source-image.jpg" data-src="" onerror="if(!this.dataset.load) {this.src='/fail-fallback-source-image.jpg'; this.dataset.load = 1 }">
dangerous, make sure the default image there. otherwise will call infinitively.
can this work too on an iframe?
Thank !!!! This work on Safari , Firefox and Chrome.
Cool post!
Can you post something about styling broken images?
I have seen other posts on the internet, and I know it is possible, but I’d like to see your version :)
Now every solution i find from your site works and are very effective, i just want to appreciate your hard work.
Thanks Alot