Search code examples
javascriptfilehtmlunobtrusive-javascriptfileapi

How to use HTML5 File API with Unobtrusive JavaScript?


I would like to use the HTML5 File API with unobtrusive JavaScript. But I can only get it working by calling JavaScript functions from the HTML. Is there any way to use the File API with unobtrusive JavaScript?

The File API is not supported by all browsers, but I have tried this in Google Chrome and in Firefox.

From the documentation this works:

<input type="file" id="input" onchange="handleFiles(this.files)">

And I have tried with this unobtrusive JavaScript that doesn't work:

window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

A complete example is below, and testable on jsFiddle.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
window.onload = function() {
    var input2 = document.getElementById('input2');
    input2.addEventListener('onchange', handleFiles);
}

function handleFiles(e) {
    alert('got files');
}
</script>
</head>
<body>
<h1>Test</h1>
<input type="file" id="input1" onchange="handleFiles(this.files)"/>
<input type="file" id="input2"/>
</body>
</html>

Solution

  • Try:

    window.onload = function() {
        var input2 = document.getElementById('input2');
        input2.addEventListener('change', handleFiles,false);
        //                       ^not onchange        ^older firefox needs this
    }
    

    jsfiddle here