JavaScript - Simple Image Upload Preview
Submitted by razormist on Friday, June 7, 2019 - 12:21.
In this tutorial we will create a Simple Image Upload Preview using JavaScript. This code can animate a flip effect on the images when the user click the button. The code use FileReader() a built-in JavaScript function that read the image properties that enable to send the image source to bind the html element. This is a user-friendly program feel free to modify it.
We will use JavaScript to add some new feature to the website interface by actually written into an HTML page. It is what gives your page a different interactive elements and animation that engage a user.
There you have it we successfully created a Simple Image Upload Preview using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting Started:
This is the link for the bootstrap that i used for the layout design https://getbootstrap.com/. And this is the link for the jquery that i used in this tutorial https://jquery.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css">
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="col-md-6">
- <form method="POST" enctype="multipart/form-data">
- <input type = "file" id = "photo" name = "photo" />
- </form>
- </div>
- <div class="col-md-6">
- <div>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. This code will preview the uploaded image when user upload the file. To do this just copy and write these block of codes as shown below inside the text editor and save it as script.js inside the js directory- $(document).ready(function(){
- $pic = $('<img id = "image" width = "100%" height = "100%"/>');
- $("#photo").change(function(){
- var files = !!this.files ? this.files : [];
- if(!files.length || !window.FileReader){
- $("#image").remove();
- $lbl.appendTo("#preview");
- }
- if(/^image/.test(files[0].type)){
- var reader = new FileReader();
- reader.readAsDataURL(files[0]);
- reader.onloadend = function(){
- $pic.appendTo("#preview");
- $("#image").attr("src", this.result);
- alert("You uploaded uploaded an image!");
- }
- }
- });
- });
Add new comment
- 198 views