0

Why am I getting this error? This should work, what I'm trying to do is when someone selects the form on the upload the image file. Thanks

The error I keep getting is

    <html>
<body>
<script type="text/javascript">
function EL(id) { return document.getElementById(id); } // Get el by ID helper function

function readFile() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
      EL("img").src       = e.target.result;
      EL("b64").innerHTML = e.target.result;
    };       
    FR.readAsDataURL( this.files[0] );
  }
}

EL("inp").addEventListener("change", readFile, false);
</script>
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img">
</body>
</html>

But it was not working fine

  • 1
    Put the script down below the targeted element so that it exists when the script runs. –  Aug 04 '16 at 14:08
  • Before the dom is ready you are trying to get the element, that's why its giving the error. – The_ehT Aug 04 '16 at 14:10
  • https://jsfiddle.net/focwd2p6/ working fine – Hassan ALi Aug 04 '16 at 14:12
  • @HassanALi: That's because you're running that code in an `onload` handler that jsFiddle provides because of the JS settings. –  Aug 04 '16 at 14:15

1 Answers1

3

Put your JavaScript in the below of the body. It throws error because your JavaScript first works when your DOM doesn't ready.

And it is a good practice to load all scripts at the end of the body

<html>
<body>
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img">

<script type="text/javascript">
function EL(id) { return document.getElementById(id); } // Get el by ID helper function

function readFile() {
  if (this.files && this.files[0]) {
    var FR= new FileReader();
    FR.onload = function(e) {
      EL("img").src       = e.target.result;
      EL("b64").innerHTML = e.target.result;
    };       
    FR.readAsDataURL( this.files[0] );
  }
}

EL("inp").addEventListener("change", readFile, false);
</script>

</body>
</html>
Suren Srapyan
  • 57,890
  • 10
  • 97
  • 101