I'm having success using this code to display a picture preview before uploading. However, I am interested in organizing the script by placing it within an external file or within the html-head section. I am having trouble figuring out how to accomplish this. I believe my issue lies with this particular segment:
reader.onload = (function(theFile) {...
Any help or guidance on this matter would be greatly appreciated :)
Below is the corresponding html code:
<!doctype html>
<html>
<head>
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
document.getElementById('list').innerHTML = "";
//The issue may lie with the ".onload" functionality?
reader.onload = (function(theFile) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/><input type="text" name="', escape(theFile.name), '-title" placeholder="title" /><input type="text" name="', escape(theFile.name), '-description" placeholder="description" />'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>