HomeCSSImage Upload With Javascript

Image Upload With Javascript

Introduction:

In this tutorial, you will learn how to create a simple image up loader using JavaScript. This feature allows users to select an image file from their device and instantly preview it on the web page. This technique is useful for image upload forms, allowing users to see what they are about to upload before submitting it.

Things You Will Learn:

By the end of this tutorial, you will learn:

  • How to work with file inputs in HTML.
  • How to dynamically update an image’s src attribute using JavaScript.
  • How to utilize the URL.createObjectURL method to create temporary URLs for image preview.

Video Tutorial:

If you prefer to learn by watching a video tutorial over reading this lengthy blog post you can watch the video tutorial here down below. Also do not forget to subscribe to my YouTube channel where I post tips, tricks and tutorials related to web development regularly.

 

Project Folder Structure:

Now before we move on to actual coding we create a project folder structure. We name the project folder as – ”Image Upload With Javascript”. Within this folder we have 3 code files and some image files. These files are:

  • index.html
  • style.css
  • script.js

HTML:

We begin with the HTML code. Copy the code below and paste it into your HTML document.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Image Upload</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <img src="default.png" />
    <input type="file" />
    <script src="script.js"></script>
  </body>
</html>

 

CSS:

Next, we style our game using CSS. For this copy, the code provided to you below and paste it into your stylesheet.

img {
  height: 150px;
  width: 150px;
  border-radius: 50%;
  object-fit: cover;
}

 

JS:

Finally, we add functionality using Javascript. For this once again copy the code below and paste it into your script file.

const image = document.querySelector("img");
input = document.querySelector("input");
input.addEventListener("change", () => {
  image.src = URL.createObjectURL(input.files[0]);
});

 

Conclusion:

You have now created a simple and effective image upload and previewer with just a few lines of code. This feature is especially useful for forms that involve image uploads, enhancing the user experience by allowing them to preview their images before submitting. Feel free to customize the styling or extend the functionality further. Happy coding!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

19 − fourteen =

Most Popular