Wojciech Maj
Wojciech Maj

Reputation: 1102

Function that checks width of an image loaded by user randomly returns 0

I was trying to write a function that would check if the image I chose via input[type=file] is exactly 700 px wide and if not - reject this image. I succeeded, however, sometimes this function randomly returns 0 and I need to load the same image a couple of times until it reads its width correctly. Any ideas on how to improve this code? Thanks in advance!

    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = new Image;
            img.src = e.target.result;
            if(img.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + img.width + " px wide. Try again!");
                input.value = "";
            }
        };
        reader.readAsDataURL(input.files[0]);
    }

Upvotes: 1

Views: 104

Answers (1)

Archy Will He
Archy Will He

Reputation: 9767

Use .onload so the function will only be triggered when the image is loaded.

 if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var img = new Image;


            img.onload = function(){
            if(img.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + img.width + " px wide. Try again!");
                input.value = "";
            }
          }


            img.src = e.target.result;
        };
        reader.readAsDataURL(input.files[0]);
    }

Or you can add an event listener:

img.addEventListener("load", function() {
     if(this.width == 700) {
                DoSomeStuff();
            } else {
                alert("This image has to be 700 px wide, but is " + this.width + " px wide. Try again!");
                input.value = "";
     }
}); 

But for ie only ie9 or above support .addEventListener, so for ie8 or below use .attachEvent

img.attachEvent("onload", function() {});

You can do an if-statement to check if browser supports .addEventListener:

if (img.addEventListener)
//return false if broswer does not support

Upvotes: 3

Related Questions