Q:

rendering image for preview from selected file in file input tag

Now I have a form field:
<input id="my_img_field" type="file"/>

After I select the image in the browser, I want to render the selected image file on the target img tag:
<img id="image_preview" />

But I want to do this after the $('#my_img_field').change event, i.e. I may want this done when I click some button later. 
I heard that this could be done using HTML5 technique. Can someone teach me how?

A:

the code in vanilla js
var file = document.getElementById('my_img_field').files[0]
    var fr = new FileReader()
    fr.readAsDataURL(file)
    fr.onload = function(e) {
      var img = document.getElementById('image_preview')
      img.src = this.result
    } 

A:

The following approach will work:
var file = $('#my_img_field')[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e) {
    var img = $('#image_preview');
    img.attr('src', this.result);
}

