preview image before uploading to server using javascript

JavaScript |

9th Aug, 2019

Click here to share

How to preview an uploaded image before it is uploaded by a user

Welcome again to another awesome tutorial project on javascript. In this lesson we will be creating a plugin which can be used to upload an image and when the user have uploaded it the image will be displayed to him before it will be sent to the server.

Some of the requirements for this lesson include the following

  1. Introduction to javascript
  2. Knowledge of some javascript window object
  3. Introduction to html
  4. Knowledge of html.
  5. Little knowledge of css

With that let us get started

First thing we have to create a folder and in it, we will create two files one named index.html and the other named image.js

Our html file will just contain a simple html mark up like the one shown below. Here we include the css and javascript file

Also it consist of two file input fields one for multiple file and the order for choosing only a single image.

Now let’s open our image.js.

The image.js file is where we are going to be doing the major work and you have to practice rather than just copying if you really want to understand it fast.

Each line is perfectly layed out with a perfect comment that will eneable you to easily understand it and it is advisable that you type it using your favorite editor and by so doing you will understand.

What we did is that we first of all select all the element that we are going to be manipulating and assign it to a variable using javascript variable assignment method.

const is usded in the variable assignment to variables that we wont change again throught out the apploication.

let is used for variables that we will manipulate later.

Then  I created javascript eventListeners based on change of the file input field.

I also created two functions that are being called by the eventListeners. These eventListeners listen to change event on the input field and execute the associated function.

With that we have our javascript complete.

Css

In the css file I just did simple style to give the content dive some good margin and I laso give the image a sityle to give it a good width amd height so that it dosent occupy the while of the screen.

The whole code for this tutorial are hosted on git hu and if you want to download it vist the repo and download. If you have any issues you can use the issue tracker by github or ciomment here and I will attrend to you speedily.

Thank you for reading if you enjoy the lesson you can go ahead and subscribe to our mailing list so that you will be the first to receive our contents of this type when published.

 

Leave a Reply

RELATED POSTS


Total of 0 Comment