Skip to content Skip to sidebar Skip to footer

Javascript: Onload And Onerror Called Together

I'm new to JavaScript and therefore confused for the variable scope... I'm trying to load an image, and replace it with another URL when it doesn't exist. I have to do it in pure J

Solution 1:

You are calling the functions, not assigning!

img.onload = onLoadHandler();
img.onerror = onErrorHandler();

needs to be

img.onload = onLoadHandler;
img.onerror = onErrorHandler;

Solution 2:

The problem with your second example is that the image callbacks are fired when the image loads, after your other code has been evaluated. I'm really not sure what your code accomplishes, but try something like this.

  img.onload = function () {
     alert(d.name + " : loaded");
     d.src = "http://.../peopleimages/" + d.num + ".jpg";
     return doSomething(this, d);
  }
  img.onerror = function () {
     alert(d.name + " : failed");
     d.src = "http://.../images/generic.jpg";
     return doSomething(this, d);
  }

  function doSomething(img, d) {
     img.src = "http://.../peopleimages/" + d.num + ".jpg";
     alert(d.src);
     return d.src;
  };

Post a Comment for "Javascript: Onload And Onerror Called Together"