Image preview

      No Comments on Image preview

Image preview function in java-script helps user to preview the image selected by input type=”file”.

Image preview -markup

HTML:

<input type="file" accept="image/*"  onchange="previewFile(event)" name="image1" id="image1">
<br>
<img id="output"  src="../images/picture.png"  height="100" width="100" alt="Image preview"/>

In the markup, we have first placed input type=file to make user select an image. accept="image/*" specifies that the file selected should be an image.The next line that is the img tag is used to hold the preview of image file. You can set the height and width attributes according to the appearance you desire from the preview.

JS:

function previewFile(event)
{
   var output = document.getElementById('output');
   output.src = URL.createObjectURL(event.target.files[0]);
}

This is the function that is triggered onchange of the value of input type file. This creates an object of the file selected and assigns it to the source of output img tag.

Demo:

See the Pen Creating Image-preview function in java-script by scanfcode (@scanfcode) on CodePen.

Summary
Image preview
Article Name
Image preview
Description
Image preview function in java-script helps user to preview the image selected by input type="file". Get complete code here at scanfcode.com
Author
Publisher Name
Scanfcode
Publisher Logo

Leave a Reply

Your email address will not be published. Required fields are marked *