jQuery/JavaScript to replace broken images
Handle the onError
event for the image to reassign its source using JavaScript:
function imgError(image) {
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Or without a JavaScript function:
<img src="image.png" onError="this.onerror=null;this.src='/images/noimage.gif';" />
The following compatibility table lists the browsers that support the error facility:
http://www.quirksmode.org/dom/events/error.html
Replace broken images with jquery
If you're trying to do this via javascript without changing your HTML, then you can do this:
$(document).ready(function() {
function checkImg(img) {
if (img.naturalHeight <= 1 && img.naturalWidth <= 1) {
// undersize image here
img.src = "upload/no-img.jpeg";
}
}
$("img").each(function() {
// if image already loaded, we can check it's height now
if (this.complete) {
checkImg(this);
} else {
// if not loaded yet, then set load and error handlers
$(this).load(function() {
checkImg(this);
}).error(function() {
// img did not load correctly
// set new .src here
this.src = "upload/no-img.jpeg";
});
}
});
});
If you need support in IE8 (which doesn't have naturalHeight and naturalWidth), there are work-arounds described here.
Detect broken image and get src's using jquery
.error
is deprecated, need to use .on('event'
instead.
Allow error
is asynchronous, your code is not waiting for images to get loaded to send final report of broken images. Also empty src attribute on img will not trigger error or success, you need to ignore or add them separately. I have ignored them in below code.
$(document).ready(function() {
//Check Image Error var i = 0; var brokenSrc = [];
var totalImagesOnPage = $('img').not( "[src='']" ).length;
$('img').on('load', function() { increaseCount(); }).on('error', function() { var link = $(this).attr('src'); console.log('broken link : ' + link); brokenSrc.push(link); increaseCount(); });
function increaseCount() { i++; if (i == totalImagesOnPage) { finishedLoadingImages(); } }
function finishedLoadingImages() { console.log("Broken images ::", brokenSrc); $.ajax({ type: "POST", url: '/', data: { imageData: { current_url: window.location.href, broken_src: brokenSrc } }, success: function(result) { console.log(result); } }); }
});
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <script src="https://code.jquery.com/jquery-3.1.0.js"></script></head><body>
<img src="" /><img src="http://google.com" /><img src="https://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2014/05/1399880336proe-pic_400x400-96x96.jpg" /><img src="https://simplyaccessible.com/wordpress/wp-content/themes/sa-wp-2014/images/logo.svg"/>
</body></html>
Replace Broken image with text
Using the alt attribute is a good solution for this, because it is made to be there for displaying when the image is not loaded.
There is already a similar question here on Stackoverflow: How to hide image broken Icon using only CSS/HTML?
The answer is not the accepted answer, but I think it is a very nice way to do this with pure css.
The code is fine and there is also a link if you like to check the source: https://bitsofco.de/styling-broken-images/
Using JavaScript, how can I replace broken images with any other HTML data
You could 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 https://stackoverflow.com/a/34726863/100754
$( 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 to Check if an image is loaded (no errors) in JavaScript.
Or, you can do something like this if you are setting 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';
jquery replace broken image with noimage icon
Try this...
$(function() {
$("img").one("load", function() {
$(this).show();
}).each(function() {
if (this.complete) $(this).load();
}).error(function () {
$(this).unbind("error").attr("src", "noimage.gif");
}).hide();
});
On document ready it will hide every image and then run the "load" method to show them, whilst also including your error handling code.
Replace broken img with fallback picture
You should put quotes around the fallback URL (Assuming the rest of the code is working).
I would also suggest to change the error handler to a function, like this:
issuePicFront.onerror=function(e){
var replacePic = '<URL>'
this.src=replacePic;
};
Related Topics
Difference Between Client-Side and Server-side Programming
How to Pass Variables and Data from PHP to JavaScript
Download File Using an Ajax Request
How to Save an Html5 Canvas as an Image on a Server
Submit Form Without Page Reloading
How to Call PHP Functions by JavaScript
How to Bypass Access-Control-Allow-Origin
Execute PHP Function With Onclick
Why Don't Self-Closing Script Elements Work
How to Programmatically Tell an HTML Select to Drop Down (For Example, Due to Mouseover)
Get Class List For Element With Jquery
Why Is "Element.Innerhtml+=" Bad Code
How to Apply CSS to Half of a Character
How to Get the Pure Text Without HTML Element Using JavaScript