I'm attempting to implement basic drag and drop functionality into my Meteor application. I want the user to be able to drop a file (from their file system) into a specified dom element, and retrieve that file in the dataTransfer
object. Unfortunately, I can't seem to prevent the event from reloading the entire page on the drop event. Here's my basic event handler:
Template.sideBar.events({
'drop #features' : function(e, t) {
e.preventDefault();
var fileList = e.dataTransfer.files;
console.log(fileList[0]);
return false;
}
});
I've tested this with Chrome and Firefox. Am I missing something? Has anyone implemented this successfully?
Well, that was silly. I think I figured it out. You need to call preventDefault()
on the dragover
event in addition to the drop
event. Here's my working code:
Template.sideBar.events({
'dragover #features' : function(e, t) {
e.preventDefault();
$(e.currentTarget).addClass('dragover');
},
'dragleave #features' : function(e, t) {
$(e.currentTarget).removeClass('dragover');
},
'drop #features' : function(e, t) {
e.preventDefault();
console.log('drop!');
}
});
Not sure why this works, but it does (at least in Chrome).
Updating to [email protected], you also need to invoke dataTransfer.getData() method in order to fetch dropped file data (if you're using drag n' drop to upload files)
'drop #features' : function(e, t) {
e.preventDefault();
console.log('drop!');
e.originalEvent.dataTransfer.getData("text");
//without the previous line you won't be able to get dropped file data;
console.log('File name: ' + e.originalEvent.dataTransfer.files[0].name);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With