0

How would you get a status code from an image url. If the image status code is 404, I'd like to replace it with something else.

1
  • You could probably use Ajax in order to determine the exact response code if needed, however this is a heavier approach compared to Arup's answer. Commented Aug 8, 2018 at 19:45

1 Answer 1

1

You can use onload and onerror events.

<script type="text/javascript">
  function onImageLoad() {
    alert("imgOne is loaded.");
  }

  function onImageLoadError() {
    alert("imgTwo is not loaded.");
  }
</script>
<img src="http://via.placeholder.com/350x150" id="imgOne" onload="onImageLoad(this);" />
<img src="http://via1.placeholder.com/350x150" id="imgTwo" onerror="onImageLoadError(this);" />

JSFiddle.

Sign up to request clarification or add additional context in comments.

1 Comment

The only issue here is that you can't specifically associate it to a response code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.