vanilla/components/uploadForm/app.js

68 lines
2.2 KiB
JavaScript
Raw Normal View History

2025-01-17 23:59:54 +00:00
const dropArea = document.getElementById('drop-area');
const fileInput = document.getElementById('file-input');
const fileList = document.getElementById('file-list');
const clearButton = document.getElementById('clear-button');
let droppedFiles = [];
// Function to display the list of selected or dropped files
function displayFileList(files) {
fileList.innerHTML = ''; // Clear previous file list
for (let i = 0; i < files.length; i++) {
const file = files[i];
const listItem = document.createElement('div');
listItem.textContent = file.name;
fileList.appendChild(listItem);
fileInput.value
}
}
// Function to add files to the file input element
function addFilesToFileInput(files) {
for (let i = 0; i < files.length; i++) {
droppedFiles.push(files[i]);
}
// Create a new FileList (simulate it for the file input)
const dataTransfer = new DataTransfer();
droppedFiles.forEach(file => dataTransfer.items.add(file));
fileInput.files = dataTransfer.files; // Set new files to the file input
}
// Add file input menu on click
dropArea.addEventListener('click', () => {
fileInput.click();
});
// Show file list when files are selected via input
fileInput.addEventListener('change', (e) => {
displayFileList(e.target.files);
});
// Handle dropped files
dropArea.addEventListener('drop', (e) => {
e.preventDefault();
addFilesToFileInput(e.dataTransfer.files); // Add dropped files to input
displayFileList(e.dataTransfer.files);
});
// Handle clear button
clearButton.addEventListener('click', () => {
fileList.innerHTML = ''; // Clear the list of files
droppedFiles = []; // Reset the dropped files array
fileInput.value = ''; // Reset the file input element
});
// Prevent default behavior for drag-and-drop
['dragenter', 'dragover'].forEach(event => {
dropArea.addEventListener(event, (e) => {
e.preventDefault();
dropArea.classList.add('hover');
});
});
// Prevent default behavior for drag-and-drop
['dragleave', 'drop'].forEach(event => {
dropArea.addEventListener(event, (e) => {
e.preventDefault();
dropArea.classList.remove('hover');
});
});