Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • JavaScript- Hide broken image icon or set a default image icon when source image is not found

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.20k
    Comment on it

    Hello Readers,

     

    When source image is not found then it will show a broken image icon. In today's post we will learn how hide broken image icon when image URL is invalid or not found.

     

    onerror attribute of <img>  which executes JavaScript if image URL is invalid or source is not found.

     

    Lets understand with the help of example:

     

     <img src="{{product.imagePath}}" onerror="HideIcon(this);">
    <script>
       function HideIcon(element)
       {
           element.style.display = "none";
       }
    </script>

     

    In the above example image path is coming from server, if URL is invalid or the image is not found then HideIcon() function will be triggered. Which will hide the broken image icon.

     

    We can also set a default image using this onerror attribute for example:

     

    <img src="invalid_link" onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';">

     

    First set the onerror = null then pass the default image src, this will show the default image if the URL provided is invalid.

     

    Hope this will help you :)

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: