I have a working script that shows image previews when users select files for upload. Everything works fine when the JavaScript is placed inline in the HTML body. However, when I try to move this code to an external JavaScript file or put it in the head section, it stops working completely.
I suspect the issue might be related to the event handling or the way I’m setting up the FileReader callback function. The code works perfectly in its current location but fails when relocated.
Here’s my current working code:
<!DOCTYPE html>
<html>
<head>
<style>
.preview {
width: 100px;
border: 2px solid #333;
margin: 5px;
}
</style>
</head>
<body>
<input type="file" id="fileInput" name="images[]" multiple />
<div id="preview"></div>
<script>
function processFiles(event) {
var selectedFiles = event.target.files;
for (var j = 0, file; file = selectedFiles[j]; j++) {
if (!file.type.match('image.*')) {
continue;
}
var fileReader = new FileReader();
document.getElementById('preview').innerHTML = "";
fileReader.onload = (function(currentFile) {
return function(event) {
var container = document.createElement('div');
container.innerHTML = ['<img class="preview" src="', event.target.result,
'" alt="', escape(currentFile.name), '"/><input type="text" name="', escape(currentFile.name), '-caption" placeholder="Enter caption" />'].join('');
document.getElementById('preview').appendChild(container);
};
})(file);
fileReader.readAsDataURL(file);
}
}
document.getElementById('fileInput').addEventListener('change', processFiles, false);
</script>
</body>
</html>
What changes do I need to make to move this JavaScript to an external file or the head section?