Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 18,967 times

Related Categories

Detect missing images with client-side script

In previous tips, we've shown you how to determine whether a file exists programmatically by using either the MSWC.Tools object or the Scripting.FileSystemObject object. Both have their place, but what if you need to make this determination in DHTML on the client side? A good example of this situation is when you need to ascertain whether an image exists before displaying it. Nobody likes seeing broken image links, but how can you trap this condition programmatically?  In DHTML, the <img> tag fires an OnError event anytime the image cannot be loaded. This can occur either because the src attribute of the <img> element points to a file that doesn't exist, because of a timeout, or because of another error. Detecting the problem, however, allows you to take some action before the element is rendered.  You could substitute another image, change the value of the image's alt attribute, or (as shown below) simply prevent the element from being rendered at all.

<html>
  <head>
    <script language="JavaScript">
      function ImageLoadFailed() {
        window.event.srcElement.style.display = "None";
      }
    </script>
  </head>
  <body>
    <img
      src="http://localhost/images/nonexistingimage.gif"
      OnError="ImageLoadFailed()">
  </body>
</html>

James first started writing tutorials on Visual Basic in 1999 whilst starting this website (then known as VB Web). Since then, the site has grown rapidly, and James has written numerous tutorials, articles and reviews on VB, PHP, ASP and C#. In October 2003, James formed the company Developer Fusion Ltd, which owns this website, and also offers various development services. In his spare time, he's a 3rd year undergraduate studying Computer Science in the UK. He's also a Visual Basic MVP.

Comments

  • MSIE Only

    Posted by Kei on 21 Nov 2003

    This method is available in Microsoft Internet Explorer only - for Netscape compatible browsers (anything on the Mozilla code-base such as Netscape, Mozilla Firebird, etc.) wait until the image is loa...

  • Comment

    Posted by a_annunz on 18 Mar 2002

    Very nice article which resolved my problem