My CMS produces an img src="(unknown)" if an image isn't provided in the database. I would like to use javascript when this occurs to change it to img src="/images/missing.png" As a complete JS noob I have tried several hacks but none seem to work... any ideas? (there is likely to be more than one image on the page if that makes any difference)
4 Answers
This should work for you, if you use onError event for handling missing image src
<img src="main_img.png" onError="this.onerror=null;this.src='/images/missing.png';" />
I used this to solve a similar problem I had (using javascript)...
const images = document.querySelectorAll("img");
images.forEach((image) => {
let imgsrc = image.getAttribute("src");
if (imgsrc === "") {
image.src = "/images/missing.png";
}
});
if you're using php then this problem is going happen for sure you can use esc_url($url)
esc_url function solves the problem
If you're dynamically injecting the src when the page loads, you can always check and swap with placeholder if needed.
if (imgSrc === "unknown") {
imgSrc = "placeholder.png";
}