1

I am using the following snip of Javascript from another SO answer:

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            alert(this.width + " " + this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
});

I cannot figure out how to get access to those this.width and this.height variables outside of the function. I have set them equal to existing variables and the variables are always 0 or null.

dmikester1
  • 1,374
  • 11
  • 55
  • 113
  • Outside where? They're not going to give you the values you want until the image is loaded, hence the `onload` handler and I'm pretty sure you need to add the image to the DOM for it to load. –  Oct 20 '15 at 15:52
  • create a `global variable` and assign `this.width` and `this.height` in that. :P – Kaushik Oct 20 '15 at 15:53
  • `this` refers to the image object being loaded. the `onload` function is executed asynchronously. –  Oct 20 '15 at 15:55
  • I tested your code without the `_URL.createObjectURL(file)` line and just created the src with a string representing the URL, and I was able to get the width and height onload. This makes me think there's something wrong with `_URL.createObjectURL(file);` http://jsfiddle.net/gzm2xghL/ – Paul Carlton Oct 20 '15 at 16:35

2 Answers2

4

Its not really useful to just make them available outside a function since you will never really know the onload happened. You want a callback that will use those values at the appropriate time.

var _URL = window.URL || window.webkitURL;
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            someCallback(this.width, this.height);
        };
        img.src = _URL.createObjectURL(file);
    }
});

function someCallback (width, height) {
    // use those values
}

Yes you can use a global variable but again I point out you won't know when those values have been populated and could end up with problems in your code.

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
  • 4
    also, if you end up with a ton of values that you are going to pass to the callback just make them an object and pass the object. values = {width: this.width, height: this.height} etc. – Chris L Oct 20 '15 at 15:57
-1

You can also do something like this

var _URL = window.URL || window.webkitURL;
var width=""; 
var height="";
$("#file").change(function (e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            width=this.width;
            height=this.height;
        };
        img.src = _URL.createObjectURL(file);
    }
});

Now you can use height and width variable out side of your change event. now this both variables are global variable

Govinda Rajbhar
  • 2,926
  • 6
  • 37
  • 62