Displaying Image Previews in the DOM
You'll learn how to dynamically create image elements and display the file previews users select before upload.
The Core Idea
Once you've read an image file using FileReader and obtained its data URL (as you learned in the previous lesson), the next step is actually showing that preview to your users. This means creating an <img> element in JavaScript, setting its src attribute to the data URL, and inserting it into the DOM where users can see it.
Think of it like developing a Polaroid photo: the FileReader "develops" the image data into a viewable format (the data URL), and now you need to pin that photo somewhere visible (the DOM).
Creating and Displaying the Preview
After FileReader finishes reading, you'll have a data URL in the result property. Create an img element, assign that data URL as its source, and append it to a container in your page:
const fileInput = document.getElementById('fileInput');
const previewContainer = document.getElementById('previewContainer');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
// Create a new image element
const img = document.createElement('img');
// Set the src to the data URL
img.src = e.target.result;
// Optionally add styling
img.style.maxWidth = '300px';
img.style.marginTop = '10px';
// Clear previous previews and add the new one
previewContainer.innerHTML = '';
previewContainer.appendChild(img);
};
reader.readAsDataURL(file);
});
The img element immediately displays once its src is set to a valid data URL, giving users instant visual feedback about what they've selected.
Key Takeaway: Create img elements dynamically with createElement, set their src to the FileReader's data URL result, and append them to the DOM to show instant image previews before upload.