jQuery to replace broken images

Learn, what are broken images and how to replace them in a document using jQuery?
Submitted by Pratishtha Saxena, on December 23, 2022

Broken Images

Broken images are images that are not successfully loaded when the document is completely loaded. There can be different reasons for this – may be the image is no more available on the website from where the source link has been taken, or the source does not exist anymore, etc.

Not-loaded images look bad on the website; hence, we need to come up with some alternative method just in case the image is not loaded. Here comes the usage of jQuery for resolving this matter.

Using jQuery

This error, when the image is not loaded, is bonded with the jQuery bind() method, and an alternative link for the image is provided over there using the attr() method. As soon as the error in the image is detected, the function bonded to this event is fired which further replaces the broken image.

The alternative image can be the image available on your server or some other platform. You need to make sure that this alternative image link has not been removed or taken down.

We can also use AJAX along with jQuery, but for now, we are just going to use jQuery for the same. The example given below shows the replacement of the broken image using the bind() method and attr() method.

jQuery code to replace broken images

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2>jQuery to replace broken images</h2>
    <hr>
    <img style="height: 200px; width: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <img style="height: 200px; width: 200px;" id="myImg" src="https://media/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <img style="height: 200px; width: 200px;" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $("img").bind("error",function(){
            $(this).attr("src","https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=");
        });
    })
  </script>
</html>

Output:

Example 1: jQuery to replace broken images




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.