0

So I have this image element.

<img src={{this.vac-card.vac_card_url}} alt="vac-card.png" id="vac-card-image" onerror="this.style.display='none'">

<p><a href={{url}} target="_blank">Click here to download.</a></p>

You can see that if the image does not load up properly, it will show nothing. How do I have it so that the paragraph only shows if the image did not load up, but it will not show if the image loaded properly?

Nimantha
  • 5,793
  • 5
  • 23
  • 56
Delta Hex
  • 23
  • 1
  • 8

1 Answers1

2

I would make the p element hidden by default, then attach an event listener to the "error" event of the image, in which I will show the paragraph.

let img = document.getElementById("vac-card-image");
let paragraph = document.getElementById("my-paragraph");
img.addEventListener("error", () => paragraph.style.display = "block");
p { display: none }
<img src={{this.vac-card.vac_card_url}} alt="vac-card.png" id="vac-card-image" onerror="this.style.display='none'">

<p id="my-paragraph"><a href={{url}} target="_blank">Click here to download.</a></p>
isherwood
  • 52,576
  • 15
  • 105
  • 143
Michael Haddad
  • 3,609
  • 7
  • 37
  • 70
  • Well, that would be so if it did what the op wants it to, but it does not. It throws an error about not knowing what that `src` attribute is. This does not perform the actions you describe in your answer for that reason. Specifically, after it throws the syntax error, it still shows the `

    ` element.

    – Randy Casburn Nov 10 '21 at 22:34