This post will discuss how to replace broken images with JavaScript.

1. Using onerror attribute

To replace broken images with JavaScript, we first need to detect them. One way to do this is to use the onerror attribute of an <img> element, which gets fired when an error occurs while loading an image. We can assign a function to this attribute that will execute when the image fails to load. For example:

JS


HTML



Edit in JSFiddle

 
Here, this keyword refers to the current image element that triggered the error. We have passed it as an argument to our error handler function.

2. Using window.addEventListener() method

Another way to detect broken images with JavaScript is to use the error event listener, which is similar to the onerror attribute but allows us to attach multiple functions to the same event. We can use the window.addEventListener() method to register an load event listener to an image element. To check if an image is not completely loaded, we can use the complete attribute of HTMLImageElement interface. It returns true if the image has completely loaded and false otherwise. We can combine this with the naturalWidth or naturalHeight properties, which would have a value of 0 when the image fails to load.

JS


HTML



Edit in JSFiddle

3. Using jQuery

One way to replace broken images with jQuery is to use the error event handler, which is triggered when an image fails to load. We can attach this event handler to all images using the $("img") selector, and then use the attr method to change the src attribute of the broken image to a default image. For example, we can use the following code:

 
This code will replace any broken image with a default image. Alternatively, we can also use the one method instead of the on method, which ensures that the event handler is executed only once for each element. This can prevent an infinite loop if the default image is also broken. For example:

That’s all about replacing broken images with JavaScript.