Sometimes we face a requirement to show an image preview to users before uploading to a server so they can verify which image or images are selected by them and if wrong images are selected then they can remove them before uploading to a server. Social media sites and hosting platforms provide this type of functionality where users can review and change images before uploading.
We can create similar functionality for showing image previews easily using jQuery. In this article, we will take a simple example where a user can select an image file and jQuery will show a preview of selected file.
First of all, let’s define basic markup for our web page then we will add our code for showing image preview. Here, you can use the existing code or copy the below code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ImagePreview Using JavaScript</title>
</head>
<body>
<input id="image" type="file" name="image">
<div id="imageDisplay"> </div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
</body>
</html>
Here, we just added a simple input field with file type and assigned an ID to it. Also, defined HTML div element which is used to show image preview to the user.
Here, we are going to use the FileReader object to show an image preview. The FileReader allows web applications to asynchronously read the contents of users’ files, using File or Blob objects to specify the file or data to read, which means that your program will not stall while a file is being read. It will commonly be used to deal with large files.
Following is a code sample to create a new instance of FileReader.
var fr = new FileReader();
Here, we have bound input with a change event and applied our logic to that function. The change event will be triggered when the user selects an image file. Let’s take an example to create our functionality. Add the below code at the end of the body tag.
$("#image").on('change', function () {
var fr = new FileReader();
if (typeof (FileReader) != "undefined") {
var imageDisplay = $("#imageDisplay");
imageDisplay.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(imageDisplay);
}
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("Your browser does not support FileReader.");
}
});
In the above code, first of all, we have defined on change event, and when on change event triggers it will create a new instance of FileReader. Then empty image displays div. At last, it will create a new image element and append it to the image display image.
Conclusion
In this article, we have taken a simple example to show an image preview to a user using jQuery and FileReader-based logic. There are many ready to use a library to perform this task easily.