18

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>';
Aurelio De Rosa
  • 21,856
  • 8
  • 48
  • 71
jprim
  • 1,293
  • 2
  • 16
  • 21
  • 1
    Define "broken image"? I don't understand. – Pekka Sep 09 '10 at 08:52
  • If the item.image is from a broken url. For instance when it shows the read X: http://img807.imageshack.us/img807/8431/brokenimage.png – jprim Sep 09 '10 at 08:56

2 Answers2

48

You can use the onerror handler. In the inline form, it looks like this:

<img src="someimage.jpg" onerror="this.style.display='none';" />
Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222
  • Hi Piskvor, thank you very much. I tried that and it throughs me back errors: if (item.image) historyHtml += ''; – jprim Sep 09 '10 at 08:57
  • 2
    @jprim : "errors" is annoyingly vague. What exactly happens when you try this? – spender Sep 09 '10 at 08:58
  • 3
    @jprim : You're not escaping quotes correctly. Try this: if (item.image) historyHtml += '' – spender Sep 09 '10 at 09:00
  • @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? – Piskvor left the building Sep 09 '10 at 09:05
  • @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. – oezi Sep 16 '10 at 11:06
  • Works on blazor; no need to do fancy stuff – kite Jan 12 '22 at 15:05
8

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>
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Hi Pekka, thanks for your help. If I put that piece of code in the link, it still gives me errors. – jprim Sep 09 '10 at 09:00
  • Syntax error within Dreamweaver when developing. I got it from Spender below. Thanks. – jprim Sep 09 '10 at 09:05
  • 1
    @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 – Pekka Sep 09 '10 at 09:07
  • 1
    Much better as this allows you to show the image should you update the src with a valid image – Mike Bryant Jul 16 '14 at 13:44