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)
Asked
Active
Viewed 3.1k times
12
-
2You need to explicitly post what you have done already. – Chazeon Feb 21 '17 at 17:25
-
And what CMS you are referring to? What didn't work? – Chazeon Feb 21 '17 at 17:26
4 Answers
23
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';" />

A l w a y s S u n n y
- 36,497
- 8
- 60
- 103
2
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";
}
});

santiagocodes
- 21
- 2
0
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

mod7ex
- 874
- 9
- 27
-2
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";
}

Peter Chon
- 42
- 4
-
This does not work if src value is (unknown) due to an error while loading, or if a src value is not provided. So this does not answer the question. – SebaGra Nov 02 '17 at 14:17