Skip to content

Instantly share code, notes, and snippets.

@markusand
Created December 24, 2018 16:54
Show Gist options
  • Save markusand/0d97366efe04e4aee101f62700cb30f2 to your computer and use it in GitHub Desktop.
Save markusand/0d97366efe04e4aee101f62700cb30f2 to your computer and use it in GitHub Desktop.
Vue.js directive to trigger an event when a file is dropped on an element
export default {
bind(el, bindings) {
el.dragEvents = ['dragenter', 'dragover', 'dragleave', 'drop'];
el.dragEvents.forEach(dragEvent => {
el.addEventListener(dragEvent, (event) => {
if (!el.classList.contains(dragEvent)) {
el.classList.remove(...el.dragEvents);
el.classList.add(dragEvent);
}
event.preventDefault();
event.stopPropagation();
}, false);
});
el.addEventListener('drop', (event) => {
const file = event.dataTransfer.items
? event.dataTransfer.items[0].getAsFile()
: event.dataTransfer.files[0];
const fakeFileEvent = { target: { files: [file] } };
bindings.value(fakeFileEvent);
}, false);
},
unbind(el) {
el.dragEvents.forEach(dragEvent => {
el.removeEventListener(dragEvent);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment