0

i try to get image width and height returned from a function, but every time it get's returned as undefined, if i console.log values in the function it shows up, but it returns undefined every time.

The main problem i suspect is with scope, because it is a nested function, but i am not really sure, if thats the case.

JS code

  //get image width and height
    $(document).ready(function(){
      //object method
      function dimensions($width, $height){
        this.getWidth = $width;
        this.getHeight = $height;
      }
      //gets image data
      function readURL(input) {
          var reader = new FileReader();
          var image  = new Image();
          reader.onload = function (e) {
            image.src = e.target.result;
          }
          reader.readAsDataURL(input.files[0]);
          return image;
      }
      //gets image dimensions (width height)
      function getImageDimensions($img){
        var $dimensions;
          $img.onload = function(){
          $dimensions = new dimensions($img.width, $img.height);
        }
          return $dimensions;
      }

  $("#imgInp").change(function(){
    alert(getImageDimensions(readURL(this)));
  });
  });

Html code

  <form id="form1" runat="server">
    <input type='file' id="imgInp"  accept="image/*"/>
  </form>

Can anyone explain to me why it doesn't return a object, but returns undefined?

1 Answers1

0

that's because your image doesn't have width or height until it is rendered in the DOM. So you are right to put the instanciation in a onload handler. The thing is that handler is triggered only when your images load, but your execute the return line before. In other words you execute this line

return $dimensions;

before this function

 $img.onload = function(){
      $dimensions = new dimensions($img.width, $img.height);
    }

put the return in $img.onload like this:

 $img.onload = function(){
         return new dimensions($img.width, $img.height);
        }
Fanyo SILIADIN
  • 802
  • 5
  • 11