Steve Alereza
Steve Alereza

Reputation: 153

Change image src on error with JavaScript

I have an image that sometimes returns a 404 error. To get the image to load, it usually works if the image src is slightly modified, for example adding "?reload=true" to the end of it. How do I do this using JavaScript?

<img src="example.com/image.png" onerror="reloadImage()">

<script>

function reloadImage() {

    // Set img src to "example.com/image.png?reload=true"

}

</script>

Upvotes: 3

Views: 3990

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Try passing the element into the function, also clear the error event else it could infinite loop.

function reloadImage(img) {
  img.onerror = null

  let url = new URL(img.src)
  url.searchParams.set('reload', 'true')
  img.src = url.toString()
}
<img src="example.com/image.png" onerror="reloadImage(this)">

The ideal solution would be to track down why it's erroring in the first place and fix that.

Upvotes: 4

Related Questions