How To Preview User selected Image In Javascript And HTML | letsbug
Hi everyone in this article we are going to see how we can implement the preview image feature in our simple web application using simple javascript.
Before we start make sure you are good at javascript and html in general. This is not a html or css tutorial so we will not focus on that. Our focus is to just implement preview feature in javascript so that you can you it in your project however you like.
So let's get started by
Main index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Input image previewer</title></head><body><input type="file" id="input" /><div class="preview"></div></body></html>
Above is the code that we have in our html file which is just basic html. And this is where we will add all our code we are not using external stylesheet or javascript file every thing will be in same file.
Styles For the input and Image
<style>.preview img {width: 30%;height: 30%;}input {width: 100%;height: 100%;border: none;background-color: transparent;outline: none;}</style>
As you can see we just have basic styling to the page
Image preview feature in javascript
<script>//display input file img in previewconst input = document.getElementById('input');input.addEventListener('change', function (e) {const preview = document.querySelector('.preview');const file = e.target.files[0];const reader = new FileReader();reader.onload = function (e) {preview.innerHTML = `<img src="${e.target.result}" alt="">`;}reader.readAsDataURL(file);})</script>
This code in the javascript is core of our project. In the above code add a event listener on our input and then whenever there is change in the input we trigger a arrow function callback with the event parameter.
In the function we first take the reference of the image preview container and then take the file from the input. Next comes creating a new file reader from the FileReader() class in javascript.
Then we add function on the reader onload event and pass the event object to the function where we set the preview elements inner HTML to the img tag with the image selected by the user.
Then we call the reader.readAsDataURL and pass the file to it. And that all that we need.
But now lets look at the output result that we will get from the above code:
Output:
before the user selects the image |
Output after the user has selected the image |
Comments
Post a Comment