0

I've read numerous posts and articles and tried both the JS-only onLoad method and using JQuery's .load(function() { way of going about things, but I can't find a good way to load an image quietly in the background and then do something once I know its actual width.

At this point I've got it all the way down as simple as I can get it, and it still returns "0":

bgImg = new Image();
bgImg.src = "./img/car-and-truck.gif";

bgImg.onload = imageLoaded();

function imageLoaded() {
    alert(bgImg.width);
}
dcgenjin
  • 1,108
  • 3
  • 12
  • 25

1 Answers1

2

Use this instead:

bgImg.onload = imageLoaded;

You are calling imageLoaded immediately which you do not want to do.

KJ Price
  • 5,774
  • 3
  • 21
  • 34
  • This change works, but why does it work? Why do you have to call the function without parentheses? – dcgenjin Jul 14 '14 at 23:20
  • You are using the function as a closure. So, instead of calling it immediately, you are passing it as a variable so that when `bgImg.onload` is ready to be called (when that image loads), `bgImg.onload` will be pointing to your `imgLoaded` function. Another way of thinking of it is that you want `bgImg.onload()` to run your function `imageLoaded()`. If you have `bgImg.onload = imageLoaded()`, then `bgImg.onload()` will only run whatever `imageLoaded()` returned when it was called. – KJ Price Jul 15 '14 at 14:45
  • This is a good place to figure out what is going on with your `imageLoaded` closure: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work. Check out the second answer. Think of bgImg.onload as the function that is looking for the closure. – KJ Price Jul 15 '14 at 14:48