0

I want to upload an image from a file browser dialog .I want the image to be previewed as the user selects the image.It is working in jsfiddle but it isn't working in my project .

The error is

"Uncaught TypeError: Cannot read property 'addEventListener' of null"

I don't know how to solve it. Please help me?

function handleFileSelect(evt) {
  var files = evt.target.files; // FileList object

  // Loop through the FileList and render image files as thumbnails.
  for (var i = 0, f; f = files[i]; i++) {

    // Only process image files.
    if (!f.type.match('image.*')) {
      continue;
    }

    var reader = new FileReader();

    // Closure to capture the file information.
    reader.onload = (function(theFile) {
      return function(e) {
        // Render thumbnail.
        var span = document.createElement('span');
        span.innerHTML = ['<img class="thumb" src="', e.target.result,
          '" title="', escape(theFile.name), '"/>'
        ].join('');
        document.getElementById('previewImg').insertBefore(span, null);
      };
    })(f);

    // Read in the image file as a data URL.
    reader.readAsDataURL(f);
  }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
  border: 1px solid #000000;
  height: 75px;
  margin: 10px 5px 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='file' id="files" name="image" multiple="multiple" />
<div id='previewImg'></div>
Rakesh
  • 104
  • 1
  • 11
Khin san
  • 99
  • 1
  • 2
  • 7
  • Can you post your fiddle link too? Thanks – bipen Dec 11 '17 at 08:53
  • Possible duplicate of [Cannot read property 'addEventListener' of null](https://stackoverflow.com/questions/26107125/cannot-read-property-addeventlistener-of-null) – CBroe Dec 11 '17 at 08:58
  • Search this `"Uncaught TypeError: Cannot read property 'addEventListener' of null"` in google.. you probably find a solution – Pedram Dec 11 '17 at 08:59

1 Answers1

0

I assume that your document.getElementById ('files') command is running before the page is fully renderd, so the selector can not find any element on the page, and you cant add addEventListener to no elements.

You have to put the selector inside document loaded function, like so:

document.addEventListener('DOMContentLoaded', function(){ 
    document.getElementById('files').addEventListener('change', handleFileSelect, false);
}, false);
Elad
  • 2,087
  • 1
  • 16
  • 30