-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinput-file.js
64 lines (54 loc) · 1.76 KB
/
input-file.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'use strict';
var InputFile = function() {
// Set options
if (arguments[0] && typeof arguments[0] === 'object') {
this.options = arguments[0];
}
// Get all the file input fields
var fields = document.querySelectorAll('input[type="file"]');
for (var i = 0; i < fields.length; i++) {
this.createField(fields[i]);
}
};
InputFile.prototype.createField = function(field) {
var options = this.options || {};
// Create drop area
var dropArea = document.createElement('div');
dropArea.className = 'inf__drop-area';
field.parentNode.insertBefore(dropArea, field);
dropArea.appendChild(field);
// Create button
var btn = document.createElement('span');
btn.className = 'inf__btn';
btn.innerText = options.buttonText || 'Choose files';
dropArea.insertBefore(btn, field);
// Create hint element
var hint = document.createElement('span');
hint.className = 'inf__hint';
hint.innerText = options.hint || 'or drag and drop files here';
dropArea.insertBefore(hint, field);
// Highlight drag area
addMultiEventListener(field, 'dragenter click focus', function() {
dropArea.classList.add('is-active');
});
// Back to normal state
addMultiEventListener(field, 'dragleave drop blur', function() {
dropArea.classList.remove('is-active');
});
// Update inner text
field.addEventListener('change', function() {
var filesCount = field.files.length;
if (filesCount === 1) {
hint.innerText = field.value.split('\\').pop();
} else {
hint.innerText = filesCount + ' ' + (options.message || 'files chosen');
}
});
};
// Listens to multiple events
function addMultiEventListener(el, e, fn) {
var events = e.split(' ');
for (var i = 0; i < events.length; i++) {
el.addEventListener(events[i], fn, false);
}
}