4

How can I detect that an image was failed to be load in Elm?

I use img [ src "/path/to/image" ] and would like to know if the image failed to load. In plan old JavaScript I would register to onError event of img but I don't see onError in Elm.

Ido Ran
  • 10,584
  • 17
  • 80
  • 143

1 Answers1

5

You can use Html.Events.on to capture an image load error.

You will need a Msg value to indicate that the image failed. Here I'll call that ImageError:

img [ src "/path/to/image", on "error" (Json.Decode.succeed ImageError) ] []

The use of Json.Decode.succeed may look confusing in this context (after all, you're trying to capture an error, so what is succeed doing there?), but that's just part of the JSON decoding package. It basically means to ignore the error javascript value passed as the first parameter by the DOM event and use the ImageError Msg.

Here is an example of capturing the error event.

And here is another example which captures both the error and load events. You can change the image src to a good or bad URL to see what happens in either case.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97