bento bento - 2 months ago 27
Javascript Question

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?

Answer

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