amgad atef
amgad atef

Reputation: 25

jQuery onload function is not work at all

i have tried this example and doest work especially in img.onload where is the problem here

after edited and remove () from img.load()

function displayPreview(files)
{ var file = files[0];
 var img = new Image();
 var sizeKB = file.size / 1024;
 img.onload = function(){ 
 alert("Size: " + sizeKB + "KB\nWidth: " + img.width + "\nHeight: "+  img.height); 
  alert("image is loaded"); } 
 img.src = _URL.createObjectURL(file);
 }

Upvotes: 0

Views: 58

Answers (2)

Satpal
Satpal

Reputation: 133453

Remove () after img.onload, When you use () with function name you are invoking it. You need to define the onload function

EDIT:

You can use FileReader API.

The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer.

Its method FileReader.readAsDataURL()

The readAsDataURL method is used to read the contents of the specified Blob or File.

Note: It works in Modern browsers

$(document).ready(function() {

  $('#file').change(function(e) {

    var file = this.files[0];
    var sizeKB = file.size / 1024;

    var img = new Image();
    img.onload = function() {
      alert("Size: " + sizeKB + "KB\nWidth: " + img.width + "\nHeight: " + img.height);
    }


    var reader = new FileReader();
    reader.onload = function(e) {
      $('#imagedisplay').attr('src', e.target.result);
      img.src = e.target.result;
    }

    reader.readAsDataURL(file);

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="file" name="file" />
<img id="imagedisplay" src="" />

Upvotes: 0

Sebastian Simon
Sebastian Simon

Reputation: 19535

Remove the () after img.onload. () is for executing a function, not assigning.

Upvotes: 1

Related Questions