Hide broken images using jQuery in asp.net - SQL Programmers

Hide broken images using jQuery in asp.net

12/06/2011

It is unprofessional and unappealing to see a broken image (Red Cross) on a website. This can happen for a number of reasons, such as when there are loading problems, server problems or when the image doesn’t exist. 

To avoid this problem the broken image can be hidden or a default image can be loaded.  The examples below illustrate how to avoid having a broken image on your website.

Hide images using error function

When the image does not exists in the specified path  or when there is a problem in loading the image, the error function can be used and we can hide the image control.

The following code is used to hide an image in jquery.

$("#<%=ImgShow.ClientID%>").error(function ()
{
    $(this).hide();
});

Execute a function after image load

Similarly you can execute a function, event or method once the image is loaded.

In following code the load() function is fired once the image is loaded.

$("#<%=ImgShow.ClientID%>").attr("src", $("/Images/default.png");

$("#<%=ImgShow.ClientID%>").load(function ()
{
$(this).show();
});