0

Not too sure why but I figured someone out here can educate me a bit on this. I am looking to set a global variable based off a jQuery loaded object. In my case I am loading an original image size from the server so I can proportionally resize it programatically. But I am stumped as to why I can alert or console log the height and width but cannot set a variable to those retrieved values outside the callback function?

HTML:
<img src='someimage.jpg' />

JS/jQuery:
var imgHeight, imgWidth;

$("img").load(function() {
    imgHeight = $(this).height();
    imgWidth = $(this).width();
    console.log(imgWidth + " x " + imgHeight); // this works
});

console.log(imgWidth + " x " + imgHeight); // this does not

Is this a timing issue and what would be a better solution to load the image and set a variable based on that response?

Paul
  • 1,527
  • 2
  • 16
  • 24
  • That is because you are using $(this).width(); within the function – imbondbaby Jun 24 '14 at 15:41
  • `load` is asynchronous so in the 2nd example your code is trying to log vars that are empty because it is run before `load` has completed. – Andy Jun 24 '14 at 15:43
  • It has nothing to do with scope, only with timing. You are trying to access the values **before** they have been set. – Felix Kling Jun 24 '14 at 15:44
  • Check the answer to this SO question also: http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached. As per jQuery documentation (http://api.jquery.com/load-event/), the `jQuery.load()` event can cease to fire for images that already live in the browser's cache. – IronGeek Jun 24 '14 at 16:05
  • So basically the load is happening after the rest of the code or before the rest? is the console log within the function first or second? – Paul Jun 24 '14 at 16:07
  • Can't you find this out by simply looking at the console? In which order do the `console.log` statements appear? – Felix Kling Jun 24 '14 at 17:29

1 Answers1

0

This is because the .load function runs once the image has been loaded. The console.log outside of load is trying to log variables that have no value.

edhedges
  • 2,722
  • 2
  • 28
  • 61