Search code examples
javascriptpreventdefault

preventDefault(); doesn´t have any effect on a drop event


I have a picture-upload-<div> where the user can drop images. The preventDefault(); on that <div>-element works fine.

But when the user drops the picture outside of the <div> the browser opens it.

To prevent that I added:

$(document).ready(function(){

    $('body').on('drop', function(e){
        e.preventDefault();
    });
}); 

The eventhandler gets triggered, but the preventDefault();-action does have no effect. The browser always loads the picture.


Solution

  • You should specify a default parameter. Also add a dragover event listener:

    $(() => {
      $("body").on("drop", (e = event) => e.preventDefault())
          .on("dragover", (e = event) => e.preventDefault());
    });