-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput.js
More file actions
71 lines (58 loc) · 2.12 KB
/
input.js
File metadata and controls
71 lines (58 loc) · 2.12 KB
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
65
66
67
68
69
70
71
document.querySelectorAll('.drop-zone__input').forEach(inputElement => {
const dropZoneElement = inputElement.closest('.drop-zone')
dropZoneElement.addEventListener('click', e => {
inputElement.click()
})
inputElement.addEventListener('change', e => {
if (inputElement.files.length) {
updateThumbnail(dropZoneElement, inputElement.files[0])
}
})
dropZoneElement.addEventListener('dragover', e => {
e.preventDefault()
dropZoneElement.classList.add('drop-zone--over')
})
;['dragleave', 'dragend'].forEach(type => {
dropZoneElement.addEventListener(type, e => {
dropZoneElement.classList.remove('drop-zone--over')
})
})
dropZoneElement.addEventListener('drop', e => {
e.preventDefault()
if (e.dataTransfer.files.length) {
inputElement.files = e.dataTransfer.files
updateThumbnail(dropZoneElement, e.dataTransfer.files[0])
}
dropZoneElement.classList.remove('drop-zone--over')
})
})
/**
* Updates the thumbnail on a drop zone element.
*
* @param {HTMLElement} dropZoneElement
* @param {File} file
*/
function updateThumbnail(dropZoneElement, file) {
let thumbnailElement = dropZoneElement.querySelector('.drop-zone__thumb')
// First time - remove the prompt
if (dropZoneElement.querySelector('.drop-zone__prompt')) {
dropZoneElement.querySelector('.drop-zone__prompt').remove()
}
// First time - there is no thumbnail element, so lets create it
if (!thumbnailElement) {
thumbnailElement = document.createElement('div')
thumbnailElement.classList.add('drop-zone__thumb')
dropZoneElement.appendChild(thumbnailElement)
}
thumbnailElement.dataset.label = file.name
// Show thumbnail for image files
if (file.type.startsWith('image/')) {
const reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
thumbnailElement.style.backgroundImage = `url('${reader.result}')`
}
} else {
thumbnailElement.style.backgroundImage = null
}
}