How do I hide broken images in javascript?
12,960
Solution 1
You can use the onerror handler. In the inline form, it looks like this:
<img src="someimage.jpg" onerror="this.style.display='none';" />
Solution 2
As @piskvor says, actually loading the image in an img tag is the only way of finding out whether the URL is broken or not. The error
event gets fired if loading fails.
But looking at your code, maybe the opposite approach makes most sense: Hide the <a>
by default, and show it in the onload
event of the image.
Abridged:
<a href=".." id="image228" style="display: none">
<img src="..." onload="this.parentNode.style.display = 'block'">
</a>
Related videos on Youtube
Author by
jprim
Updated on May 02, 2022Comments
-
jprim almost 2 years
I have my image inside an if statement:
if (item.image) historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><img src="' + item.image +'" width="111px"/></a>';
-
PekkaDefine "broken image"? I don't understand.
-
-
jprim over 13 yearsHi Piskvor, thank you very much. I tried that and it throughs me back errors: if (item.image) historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><img src="' + item.image +'" width="111px" onerror="this.style.display='none';" /></a>';
-
spender over 13 years@jprim : "errors" is annoyingly vague. What exactly happens when you try this?
-
jprim over 13 yearsHi Pekka, thanks for your help. If I put that piece of code in the link, it still gives me errors.
-
spender over 13 years@jprim : You're not escaping quotes correctly. Try this: if (item.image) historyHtml += '<a href=' + item.image + ' class="image" target="_blank"><img src="' + item.image +'" width="111px" onerror="this.style.display=\'none\';" /></a>'
-
jprim over 13 yearsSpender - that works perfect. Thank you very much for your help! :D
-
jprim over 13 yearsSyntax error within Dreamweaver when developing. I got it from Spender below. Thanks.
-
Piskvor left the building over 13 years@jprim: "there's an error" "what error?" "an error!" In other words, can you be a bit more specific? Does the syntax error have any more data? On which part of the code it appears to be?
-
Pekka over 13 years@jprim your're welcome. I'd suggest you familiarize yourself how to escape quotes correctly. Dreamweawver's Syntax highlighting should show you when a string is not correctly escaped
-
oezi over 13 years@jprim: if this is the answer you're looking for, why haven't you accepted it? if you do so, this will help you to get more feedback on your other questions because the peaople can see that they will be rewarded for their help.
-
Mike Bryant almost 10 yearsMuch better as this allows you to show the image should you update the src with a valid image
-
kite over 2 yearsWorks on blazor; no need to do fancy stuff