2

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>

2 Answers 2

7

Try:

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

jsfiddle here

Sign up to request clarification or add additional context in comments.

2 Comments

Why do you set the useCapture to true rather then false ?
@Raynos: no particular reason. Default is false, I'll change it. But it's not optional in some browsers (see note @ developer.mozilla.org/en/DOM/element.addEventListener), so providing a value is useful.
3

not onchange but

input2.addEventListener('change', handleFiles);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.