0

I am using HTML5 file API to get the width of an image.

Its working, and the console.log is outputting the correct amount.

I need to save the value to the variable fileWidth so I can access it outside the function. I have created an empty variable outside the function, and expected it to be updated with the alue inside the function, but whatever I try fails.

Here is my code:

var fileWidth;
var reader = new FileReader;
reader.onload = function() {
    var img = new Image;
    img.onload = function() {
        fileWidth = img.width;
        console.log(fileWidth);
    };
    img.src = reader.result;
};

reader.readAsDataURL($('#submission-file')[0].files[0]);

Can anyone see why the variable isn't being updated?

Edited Code:

var fileWidth;
var reader = new FileReader;
reader.onload = function() {
    var img = new Image;
    img.src = reader.result;
};
reader.onloadend = function() {
    fileWidth = img.width;  
};

reader.readAsDataURL($('#submission-file')[0].files[0]);

console.log(fileWidth);
8
  • 2
    Probably an async function. Commented Jun 13, 2013 at 14:52
  • Dont you need the onloadend event for reader instead ? Commented Jun 13, 2013 at 14:57
  • @ccdavies, take a look at the File APIs. Commented Jun 13, 2013 at 14:58
  • @SaintGerbil Thanks, but I tried this already. Commented Jun 13, 2013 at 15:00
  • @chrismborland Again, thanks, but thats where I came from. I am obviously doing something wrong here, but can't see it myself... Commented Jun 13, 2013 at 15:01

1 Answer 1

1

You're setting fileWidth in an asynchronous callback, this method isn't guaranteed to have executed prior to your accessing the variable.

Hint

Try putting an alert in your callback and an alert right before you access the variable. See which alert is presented first.

Sign up to request clarification or add additional context in comments.

4 Comments

Ah that makes sense, but how do I ensure it has run before hand?
What @SaintGerbil said or access fileWidth once you know your onload method has been called (i.e. create an onloadend event and access it there).
@chrismborland Thank you for this answer, but I can't figure this out. I have changed my code in the question to show what I thought I needed to do, but I am obviously way off. Could you possibily explain how I can use the onloadend in this instance?
@ccdavies, I just noticed that you have nested asynchronous callbacks img.onload inside of reader.onload, which means you're not even guaranteed to have your fileWidth when reader.onload has finished its execution. Check out this jsFiddle and notice the order of execution (alerts).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.