1

Im using javascript to be able to display an image pre file upload but Im having this error...

I have a javascript function

function imageIsLoaded(e) {
    $('#image_preview_new').css("display", "block");
    var previewDiv = $('#previewing_new');
    previewDiv.attr('src', e.target.result);
}

and I am calling the function via another script, but I need to be able to pass both the event data as well as an id into that function but it doesn't seem to work...

This is what I am currently using and it works...

var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);

This is what I've been trying and it doesn't work. If try and pass the id and the event data (e, id) it tells me that "e is not defined"...

var reader = new FileReader();
reader.onload = imageIsLoaded(e, id);
reader.readAsDataURL(this.files[0]);

function imageIsLoaded(e, id) {
    $('#image_preview_new').css("display", "block");
    var previewDiv = $('#previewing_new');
    previewDiv.attr('src', e.target.result);
}

How can I get the event data as well as an id into this function.

Thanks.

LargeTuna
  • 2,694
  • 7
  • 46
  • 92

1 Answers1

3

Use .change() event, Function.prototype.bind()

function imageIsLoaded(id, e) {
  // `id` : `"abc"` , `e` : `event`
  console.log(id, e);
  // do stuff with `id`
  var previewDiv = $("#" + id);
  previewDiv.attr("src", e.target.result);
}

$(":file").change(function() {
  var reader = new FileReader();
  // set `this` to `reader` at first parameter to `.bind()`
  // pass `id` : `"abc"` at second parameter `.bind()` , 
  // called at `imageIsLoaded`
  reader.onload = imageIsLoaded.bind(reader, "abc");
  reader.readAsDataURL(this.files[0]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file">
<br />
<img id="abc" />
guest271314
  • 1
  • 15
  • 104
  • 177