Open In App

How to hide “Image not found” icon when source image is not found?

JavaScript and jQuery can be used to hide the “Image Not Found”icon when the image is not found. The basic idea is to set the display property of the image object to ‘hidden’ when an error arises. Let us consider the below HTML code which displays the GeeksforGeeks logo for demonstration purpose.
Example: In this example, we will not hide the icon of image not found. 
 




<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h2>
            Example to hide the 'Image Not Found' icon i.e.
            <img src="error.png" width="20px" />
        </h2>
        <img id="HideImg" src="geeksforgeeks-6.png" />
    </body>
</html>

Output: 
 





Methods to hide the image error icon: 
 




<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <h2>
            Example to hide the 'Image Not Found' icon i.e.
            <img src="error.png" width="20px" />
        </h2>
        <img id="HideImg" src="geeksforgeeks-6.png"
             onerror="hideImg()"/>
        <script>
      function hideImg() {
        document.getElementById("HideImg")
                          .style.display = "none";
       }
        </script>
    </body>
</html>




<html>
    <head>
    </head>
    <body>
        <h2>
            Example to hide the 'Image Not Found' icon i.e.
            <img src="error.png" width="20px" />
        </h2>
        <img id="HideImg" src="geeksforgeeks-6.png"
             onerror='this.style.display = "none"' />
    </body>
</html>   




<!DOCTYPE html>
<html>
    <head>
        <script src=
       </script>
    </head>
    <body>
        <h2>
            Example to hide the 'Image Not Found' icon i.e.
            <img src="error.png" width="20px" />
        </h2>
        <img id="HideImg" src="geeksforgeeks-6.png" />
    </body>
</html>
<script>
    $(document).ready(function () {
        $("#HideImg").error(function () {
            $(this).hide();
        });
    });
</script>

Output: All the above codes give the same output. 
 

 


Article Tags :