contentmatcher/static/js/dropzone.js

51 lines
1.8 KiB
JavaScript

// select all `<input>` elements with the class `dropzone-input` and operate on each of them
document.querySelectorAll(".dropzone-input").forEach((inputEl) => {
// select the element's (closest) parent with the class name `dropzone` (the element with the actual "dropzone" functionality)
const dropZoneEl = inputEl.closest(".dropzone");
// select the element's (closest) parent with the class name `dropzone-form` (the container of all "dropzone" functionality and the form action, in our case this is the same element)
const dropZoneFormEl = inputEl.closest(".dropzone-form");
// select the info text element inside the container
const dropZoneTextEl = dropZoneFormEl.querySelector(".dropzone-txt")
// add a `click` event listener on the dropzone to trigger the input's click event
dropZoneEl.addEventListener("click", (e) => {
inputEl.click();
});
// add a `change` event listener
inputEl.addEventListener("change", (e) => {
e.preventDefault();
console.log("change")
if (inputEl.files.length) {
// change info text
dropZoneTextEl.innerHTML = "Uploading file ...";
// submit form
dropZoneFormEl.submit();
}
});
// add to class list when we drag over the element
dropZoneEl.addEventListener("dragover", (e) => {
e.preventDefault();
dropZoneEl.classList.add("dropzone--over");
});
// remove from class list when we leave or stop dragging
["dragleave", "dragend"].forEach((type) => {
dropZoneEl.addEventListener(type, (e) => {
e.preventDefault();
dropZoneEl.classList.remove("dropzone--over");
});
});
dropZoneEl.addEventListener("drop", (e) => {
e.preventDefault();
if (e.dataTransfer.files.length) {
inputEl.files = e.dataTransfer.files;
dropZoneTextEl.innerHTML = "Uploading file ...";
dropZoneFormEl.submit();
}
dropZoneEl.classList.remove("dropzone--over");
});
});