In this article, you are going to learn two methods to automatically fix broken images using JavaScript and jQuery. We'll explore practical solutions to address this common issue in web development.

Method 1: Checking Image Availability

To start, let's create a JavaScript function that checks if an image is available or broken. This simple effective approach helps to identify broken images.

Example

<img id="myImage" src="/img.png" alt="My Image">
 <script>
   function checkImage() {
     const img = document.getElementById('myImage');
          img.onerror = function() {
          img.src = '/favicon.ico';
         };
    }
    checkImage();
 </script>
  1. The HTML includes an image element with an associated JavaScript function.
  2. The JavaScript function checkImage() checks for errors when loading the image.
  3. If an error occurs (image is broken), it handles the situation by replacing it with a default image.
<img id="myImage" src="/img.png" onerror="this.src='/favicon.ico'" alt="My Image">

Method 2: Using jQuery for Dynamic Loading

For those familiar with jQuery, this method provides a concise solution using the library's capabilities.

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<div id="imageContainer"></div>
<script>
 $(document).ready(function() {
    var imageUrl = '/image.jpg';
        $('<img>').attr('src', imageUrl).on('error', function(){
        $(this).attr('src', '/favicon.ico');
        }).appendTo('#imageContainer');
   });
</script>
  1. This method uses jQuery to dynamically load an image and handle errors.
  2. The code includes a callback function to replace the broken image with a default one.

Conclusion:

In this article, you learned two effective methods to automatically fix broken images using JavaScript. By checking image availability and dynamically loading images with jQuery, you can enhance the user experience on your website.