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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.