Explain Codes LogoExplain Codes Logo

How to preview selected image in input type="file" in popup using jQuery?

javascript
file-reader-api
blob-url
image-preview
Alex KataevbyAlex Kataev·Feb 20, 2025
TLDR

Displaying a selected image from <input type="file"> in a popup can be smoothly achieved using jQuery alongside the FileReader API. Connect a change event listener to the input, read the selected file using FileReader, and when the file is successfully read, assign the image src to present it in a modal. The protocol is depicted as follows:

$('#fileInput').change(function(e) { let file = e.target.files[0]; let reader = new FileReader(); // It's Magic! No, It's JavaScript!🧙‍♂️ reader.onload = () => $('#imagePreview').attr('src', reader.result).parent().show(); reader.readAsDataURL(file); });

Combine it with a compact HTML foundation:

<input type="file" id="fileInput"> <div id="popupModal" style="display:none;"> <img id="imagePreview" alt="Preview" /> </div>

Don't forget to include jQuery, and modify #popupModal's style to converge with your design. This procedure enhances jQuery's event handling capabilities and the FileReader for a quick image preview feature.

Enhanced technique: createObjectURL

The FileReader API provides powerful features, however, URL.createObjectURL() offers a more efficient route. As against to readAsDataURL which transforms the file into a Data URL, createObjectURL() creates a blob URL pointing to the file residing in the browser's memory, which is particularly advantageous for large images.

$('#fileInput').change(function(e) { let file = e.target.files[0]; let imageUrl = URL.createObjectURL(file); $('#imagePreview').attr('src', imageUrl).parent().show(); });

Ensure the browser compatibility and provide fallbacks if necessary. Here's an example using webkitURL for older versions of Chrome and Safari:

let imageUrl = (window.URL || window.webkitURL).createObjectURL(file);

Memory enlightenment: revokeObjectURL

When using createObjectURL(), remember to call URL.revokeObjectURL() once the image is no longer needed to free up memory.

$('#popupModal').on('hidden', function() { // Release the Kraken! I mean, memory! URL.revokeObjectURL($('#imagePreview').attr('src')); });

Dazzling the details: CSS Styling

Scintillate user interaction with the preview by predefining image dimensions and styles in CSS:

#popupModal { /* Your magic starts here */ } #imagePreview { max-width: 100%; max-height: 400px; /* Be the cool-dude coder who knows layer styles */ }

Prevent overflowing or excessive distortion that could warp the user’s view of the image. Opt for max-width and max-height to conserve the aspect ratio and provide optimal visualization.

Check mate: File type validation

Before attempting to preview, verify that the selected file is an image. Use the match method backed by a regular expression to validate file types:

$('#fileInput').change(function(e) { let file = e.target.files[0]; if(file.type.match('image.*')) { // Vision test passed! } else { alert('Please select an image file. Not your grandma’s secret recipes!'); } });

More the merrier: Multiple file selections

For applications that require multiple file handling, integrate an event listener within a loop or forEach:

$('#fileInput').change(function(e) { let files = e.target.files; for (let i = 0; i < files.length; i++) { // How about a movie marathon, err, I mean files loop? } });

Leverage closures within these loops to effectively manage scope and handle each file.

Add-ons for enhanced user experience

Whilst the basics are covered, the user experience can be elevated by incorporating progress loading indicators or overlay effects signaling the image processing.

Make it accessible by offering alt text and defining proper ARIA roles to your modal. Uphold inclusivity for all users—including those with disabilities.

Experiment with drag and drop uploads for a modernized process, supplementing the traditional file input selection.