Cathal
Cathal

Reputation: 43

Why will this only work in the body section and not in the head

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<input type="file" id="files" multiple />
<label id="list"></label>

<script>
//Interact with local files using the HTML5 file API
function handleFileSelect(evt) 
{
    //target is the element that triggered the event
    var files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    for(var i=0; i<files.length; i++)
    {
        f = files[i];
        document.getElementById('list').innerHTML += f.name + ' ' + f.type + ' ' + f.size + ' bytes ' + f.lastModifiedDate + '<br/>';
    }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>

I am just wondering why does the code not work correctly if the script section is moved from the body to the head.

The correctly working code should display the file name along with its size and other details, but when the code is moved it displays none of this.

Upvotes: 3

Views: 67

Answers (1)

Matt Greer
Matt Greer

Reputation: 62027

Because when you place it in the head, the files element doesn't exist yet. So when you call document.getElementById('files'), it returns null, causing addEventListener to crap out.

The browser builds the page top down. Most commonly you put JavaScript at the bottom because of this.

Alternatively, you can hook into the DOMContentLoaded event. Which is basically what jQuery's $(document).ready() does. Or do window.onload = function() {...} or document.onload = function() {...}.

But really, placing it at the bottom is simpler. I usually just do that.

Upvotes: 7

Related Questions