Reputation: 547
I have a div which acts as drag and drop. It has also select file functionality. When file is selected, I want a customer to be able to delete it and select another one. So I am changing the content of a div with input onchange. Problem occures wneh I want to delete a file, filebrowser opens automaticaly, and I want to prevent it. Here is my code:
HTML
<div id="drop-zone"
ondrop="drag_drop(event)"
ondragover="return false"
onclick="selectFile()"
>
<span class="drop-zone__title">Drop your file here</span>
<span class="drop-zone__subtitle">or select a file</span>
</div>
<input type="file"
name="upload-file"
id="upload-file"
accept=".pdf,.docx"
aria-invalid="false"
onchange="changeFile()"
/>
JS:
const dropZone = document.querySelector('#drop-zone')
const uploadFile = document.querySelector('#upload-file')
function drag_drop(event) {
event.preventDefault()
if (event.dataTransfer.files[0]) {
uploadFile.files = event.dataTransfer.files
dropZone.innerHTML = '<div>' + event.dataTransfer.files[0].name +
'<button class="removeFile" onclick="fileRemove(event)">
<i class="far fa-times"></i>
</button>
</div>'
dropZone.classList.add('drop-success');
}
function selectFile() {
if (uploadFile.files.length == 0) uploadFile.click()
}
function changeFile() {
dropZone.innerHTML = '<div>' + uploadFile.files[0].name +
'<button class="removeFile" onclick="fileRemove(event)">
<i class="far fa-times"></i></button></div>'
dropZone.classList.add('drop-success');
};
function fileRemove() {
dropZone.onclick='' // setting the onclick of drop-zone to none
dropZone.innerHTML = '<span class="drop-zone__title">Drop your file here</span>' +
'<span class="drop-zone__subtitle">Or select a file</span>'
dropZone.classList.remove('drop-success');
uploadFile.value = '';
dropZone.onclick= selectFile() // setting back onclick of drop-zone for selecting files
}
My fileRemove() function is not performing well. It removes the files, sets back the content of the div, but immediately reopens the file selector - I want to prevent this. I was trying with setting the onclick on and off, but that doesn't work.
Upvotes: 1
Views: 142
Reputation: 341
The issue here is this function call, which is clicking the file upload input again
function selectFile() {
if (uploadFile.files.length == 0) uploadFile.click()
}
Not sure why you need to click that input from javascript if the user can click it normally, just commenting that line will do the trick
function selectFile() {
if (uploadFile.files.length == 0){
//uploadFile.click()
}
}
Full fiddle here https://jsfiddle.net/zgranda/3scvbjmq/13/
EDIT: Updated the fiddle with your new comment, now it checks if the event.target
has the class removeFile
. Check the updated fiddle here https://jsfiddle.net/zgranda/3scvbjmq/41/
Upvotes: 1