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 preview
    const 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:

User selected image previewer - letsbug.com
before the user selects the image





user selected image previewer in javascript - letsbug
Output after the user has selected the image

Comments

Categories

Big Data Analytics Binary Search Binary Search Tree Binary To Decimal binary tree Breadth First Search Bubble sort C Programming c++ Chemical Reaction and equation class 10 class 10th Class 9 Climate Complex Numbers computer network counting sort CSS Cyber Offenses Cyber Security Cyberstalking Data Science Data Structures Decimal To Binary Development diamond pattern Digital Marketing dust of snow Economics Economics Lesson 4 Email Validation English fire and ice Food Security in India Footprints Without feet Forest And Wildlife Resources game Geography Geography lesson 6 glassmorphism Glossary Graph HackerRank Solution hindi HTML image previewer India-Size And Location Insertion Sort Internet Network Status Interview Questions Introduction to cyber crime and cyber security IT javascript tricks json to CSV converter lesson 2 lesson 1 lesson 2 Lesson 3 Lesson 6 lesson 7 Life lines of National Economy life processes Linear Search Linked List lowest common ancestor Machine Learning MCQs median in array Merge sort min and max of two numbers Moment Money and Credit My Childhood Natural Vegetation and Wildlife NCERT Network connectivity devices Network Models Network Security No Men Are foreign Node.js operator overloading P5.js PHP Physical features of India Population Prime Numbers python Quick sort R language Rain on the roof Regular Expression Resources and development reversing array saakhi science Searching Algorithm Selection sort Social Media Marketing social science Software Engineering Software Testing Sorting Algorithm Stacks staircase pattern System Concepts Text Recognition The last Leaf time converter Time Passed From A Date Todo List App Tree Trending Technologies Understanding Economic Development username and password video player Visualization water resources Wired And Wireless LAN साखी
Show more

Popular Posts

Big Data MCQs(multiple choice questions) with answers - letsbug

Digital Marketing MCQ(Multiple Choice Questions) with Answers | part 1 | letsbug

Software Engineering MCQs questions with answers - letsbug