Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventing default with drag events in Meteor

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?

like image 991
bento Avatar asked Jan 25 '13 02:01

bento


2 Answers

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).

like image 180
bento Avatar answered Nov 08 '22 03:11

bento


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);
}
like image 1
thiagoribeiro015 Avatar answered Nov 08 '22 03:11

thiagoribeiro015