1

Hi i get this tutorial from http://jsfiddle.net/AbdiasSoftware/TsxzR/ when this code be in body tag this work good but when this be in head tag this not work i am Amateur in javascript please help me

my html code :

 <input type="file" name="file" id="confirm">
 <input type="file" name="file" id="approveletter">

my javascript code :

document.getElementById('confirm').addEventListener('change', checkFile, false);
approveletter.addEventListener('change', checkFile, false);

function checkFile(e) {

var file_list = e.target.files;

for (var i = 0, file; file = file_list[i]; i++) {
    var sFileName = file.name;
    var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
    var iFileSize = file.size;
    var iConvert = (file.size / 10485760).toFixed(2);

    if (!(sFileExtension === "pdf" || sFileExtension === "doc" || sFileExtension === "docx") || iFileSize > 10485760) {
        txt = "File type : " + sFileExtension + "\n\n";
        txt += "Size: " + iConvert + " MB \n\n";
        txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
        alert(txt);
    }
}
}

thanks

nazanin
  • 729
  • 1
  • 6
  • 13
  • You should always check the console of your developer tools for the errors that are displayed. The error message is most likely `Uncaught TypeError: Cannot read property 'addEventListener' of null` or similar. – t.niese Jun 17 '17 at 20:45

2 Answers2

2

This is because the DOM isn't fully parsed yet when you place the script within the head tag.

You could wrap your code on the DOMContentLoaded event from document object, and it will work at the head tag since it will wait and will execute only when the DOM is completely loaded. However, it's recommended to place it just before the closing body tag, as you're doing, for performance purposes.

document.addEventListener('DOMContentLoaded', function () {
  // place your code here, and it will work, even if it's on the head tag
});

See also: Where should I put <script> tags in HTML markup?

Edmundo Santos
  • 8,006
  • 3
  • 28
  • 38
0

Put this JavaScript code after your javaScript libraries