How to add an image placeholder with JavaScript?

Sometimes, we want to add an image placeholder with JavaScript.

In this article, we’ll look at how to add an image placeholder with JavaScript.

How to add an image placeholder with JavaScript?

To add an image placeholder with JavaScript, we can handle the img element’s error event.

For instance, we write:

<img src='abc'>

to add an img element.

Then we write:

const img = document.querySelector('img')
img.onerror = (e) => {
  e.target.src = 'https://picsum.photos/200/300'
}

to select the img element with querySelector.

Next, we set the img.onerror property to a function that sets the img’s src property to the placeholder image’s URL.

Therefore, when the image fails to load, onerror will run and set the src attribute to the placeholder image URL.

Conclusion

To add an image placeholder with JavaScript, we can handle the img element’s error event.