JavaScript
- 1 ответ
- 0 вопросов
0
Вклад в тег
const loaders = document.querySelectorAll('.file-loader')
loaders.forEach((loader) =>
{
const dropBox = loader.querySelector('.file-loader__input-wrapper')
const input = loader.querySelector('.file-loader__input')
const files = loader.querySelector('.file-loader__files')
const refreshFiles = () =>
{
// Clear files
files.innerHTML = ''
// Make all files
Array.from(input.files).forEach(file =>
{
const el = document.createElement('li')
el.classList.add('file-lader__file')
el.classList.add('file-loader-file')
const elName = document.createElement('span')
const elDelete = document.createElement('span')
elName.classList.add('file-loader-file__name')
elDelete.classList.add('file-loader-file__delete')
elDelete.addEventListener('click', e =>
{
deleteFile(e.target.parentNode)
})
elName.textContent = file.name
elDelete.textContent = 'Удалить файл'
el.appendChild(elName)
el.appendChild(elDelete)
files.appendChild(el)
})
}
const deleteFile = (element) =>
{
let dt = new DataTransfer()
const index = getChildElementIndex(element)
// Copy all besides deleted
for(let i=0; i<=input.files.length-1; i++)
if(i !== index)
dt.items.add(input.files[i])
// Replace
input.files = dt.files
refreshFiles()
}
function getChildElementIndex(element)
{
return Array.prototype.indexOf.call(element.parentNode.children, element)
}
dropBox.addEventListener('drop', e =>
{
input.files = e.dataTransfer.files
refreshFiles()
e.preventDefault()
})
input.addEventListener('change', e =>
{
refreshFiles()
e.preventDefault()
})
})