0

I have a sample module in js that is suppose to manage Drag and Drop file upload. The code seems to work for 'dragenter' event function but when I drop the file, and 'drop' event should call the dropped function, the code always forwards to the file path.

Here is the code sample

var testModule = (function testBuilder(){
    function call(evt) {
        evt.preventDefault();
        console.log('works');
    }

    function dropped(evt) {
      evt.preventDefault();
      console.log('file dropped');
    }

    var element = document.getElementById('testBlock');

    function init() {
      element.addEventListener('dragenter', call, false); 
      element.addEventListener('drop', dropped, false);
    }

    publicAPI = {
        init: init
    };

    return publicAPI;
})();

window.onload = function() {
    testModule.init();
};

and a jsbin here https://jsbin.com/redixucate/edit?js,console,output

If anyone can figure out why it keeps redirecting the file path, I would rly appreciate it.

Teddy
  • 55
  • 2
  • 9

1 Answers1

1

Add 'dragover' event with preventDefault and it should work.

Inside your init():

element.addEventListener('dragover', over, false);

and over function:

function over(e) { 
   e = e || window.event; 
   if(e.preventDefault) {
     e.preventDefault();
   } 
}

Also add the same prevention to your other two functions ..

See https://jsbin.com/xemovariwu/1/edit?js,console,output

Also see this question/answer.

Community
  • 1
  • 1
trainoasis
  • 6,419
  • 12
  • 51
  • 82
  • 1
    That did the trick. Seems I need to cancel dragover before i can cancel drop as well. Need to stick my nose more in the documentation see if they cover this. – Teddy Mar 01 '16 at 11:29