Moving JavaScript code from inline to external file not working

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?

Your script’s trying to grab DOM elements before they’re loaded. When JavaScript runs in the head or from an external file, those HTML elements don’t exist yet. I’ve hit this same issue tons of times when moving inline scripts around. Here’s the fix - wrap your event listener in a DOMContentLoaded handler: document.addEventListener(‘DOMContentLoaded’, function() { document.getElementById(‘fileInput’).addEventListener(‘change’, processFiles, false); }); Or just move your script tag to the bottom of the body, right before the closing tag. That way all the DOM elements get parsed first. Both work great, but I like DOMContentLoaded better for keeping things organized.

u might be encountering a timing issue. try wrapping the code in a window.onload or use document.addEventListener(‘DOMContentLoaded’, …). also, consider placing the external JS just before the closing tag.

It’s a script timing issue. Your JavaScript runs before the DOM elements exist. Had the same problem last month with a photo gallery - super frustrating. Just move your script tag right before the closing body tag instead of putting it in the head. That way all your DOM elements load first, then the script runs. If you’re stuck keeping it in the head, wrap your event listener in DOMContentLoaded. But honestly? Moving the script tag is way cleaner and you won’t need those extra event handlers. Your FileReader code is fine - it’s just a timing thing.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.