Simple Image Preview Before Upload Using jQuery

Simple Image Preview Before Upload Using jQuery

Avatar photoPosted by

Introduction:

Previewing an image in most cases are very essential, most of the actions that includes and image upload has a image preview feature. Having a image preview helps the user to know if the right images is being uploaded or selected.

On today’s topic, I will show you how to create a simple image preview before upload using jQuery. JQuery is a library in javascript that is fast, small and feature-rich. It simplifies the HTML DOM traversal, manipulation, event handling, css animation, ajax by using it API that is easy to use. Almost all of the website use jQuery.

Create Upload Form:

Create a blank HTML Document and a upload form. Inside your upload form add an image tag, it will used as the image preview:

<!DOCTYPE html>
<html>
<head>
	<title>Image Upload</title>
</head>
<body>
	<div style="text-align: center;margin-top: 50px;">
		<h2>Image Preview</h2>
		<form>
			<img id="image-preview" src="#" alt="Image Preview" style="display: block;margin: auto;" />
			<input type="file" name="image" id="image">
			<button>Sumbit</button>
		</form>
	</div>
	
</body>
</html>

Add JQuery:

On your blank HTML Document add a jquery script:

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Preview Script:

After adding the jquery script, we will know create a script that will make an image preview.

First, create a function that will display the selected image:

function imagePreview(input)
		{
			//Check if there is a file that has been selected
			if (input.files && input.files[0]) {
			    var reader = new FileReader();
			    
			    reader.onload = function(e) {
			      $('#image-preview').attr('src', e.target.result);
			    }
			    
			    reader.readAsDataURL(input.files[0]); 
			 }
		}

Then, check for on change event on the file input:

$("#image").change(function () {
    imagePreview(this);	
});

Complete Code:

Here is the complete code:

<!DOCTYPE html>
<html>
<head>
	<title>Image Upload</title>
</head>
<body>
	<div style="text-align: center;margin-top: 50px;">
		<h2>Image Preview</h2>
		<form>
			<img id="image-preview" src="#" alt="Image Preview" style="display: block;margin: auto;" />
			<input type="file" name="image" id="image">
			<button>Sumbit</button>
		</form>
	</div>
	<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
	<script type="text/javascript">

		$("#image").change(function () {
    		imagePreview(this);	
		});

		function imagePreview(input)
		{
			//Check if there is a file that has been selected
			if (input.files && input.files[0]) {
			    var reader = new FileReader();
			    
			    reader.onload = function(e) {
			      $('#image-preview').attr('src', e.target.result);
			    }
			    
			    reader.readAsDataURL(input.files[0]); 
			 }
		}
	</script>
</body>
</html>