faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

99 of 117 people (85%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How to check if an image is loaded?
How to execute code when an image is loaded?
How to handle errors when an IMG/Image is attempted to load?

Mar 7th, 2000 00:55
Martin Honnen,


IMG elements and Image object have an 
  onload 
handler, an
  onerror
handler and a 
  complete
property. So to execute code when an image is loaded use
  <IMG ONLOAD="//your code here e.g alert(this.src + ' loaded')"
       SRC="whatever.gif" NAME="imageName">
for IMG elements respectively
  function imageLoadHandler (evt) {
    // your code here e.g.
    // alert(this.src + ' loaded')
  }
  var img = new Image();
  img.onload = imageLoadHandler;
  img.src = 'whatever.gif';
for Image objects.
To check whether an image is loaded use
  if (document.images['imageName'].complete)
respectively
  if (img.complete)
To handle errors when trying to load an image use the onload handler 
e.g for IMG elements
  <IMG ONERROR="// your code here e.g. 
                var alternativeSrc = 'http://whereever/whatever.gif';
                alert(this.src + ' not loadable. Trying to load ' +
                      alternativeSrc);
                this.src = alternativeSrc;"
       SRC="http://whatever/whatever.gif"
  >
respectively for Image objects
  function imgErrorHandler (evt) {
    var alternativeSrc = 'http://whereever/whatever.gif';
    alert(this.src + ' not loadable. Trying to load ' +
           alternativeSrc);
    this.src = alternativeSrc;
  }
  var img = new Image();
  img.onerror = imgErrorHandler;
  img.src = 'http://whatever/whatever.gif';