Search code examples
jquerydrag-and-droppreventdefault

Prevent the default action. Working only in chrome


Jquery:

$(document).ready(function () {
   $('input[type=file]').uploadImage();
   jQuery.event.props.push('dataTransfer');
   $(".upload-cont").bind('dragenter', function (e) {
      $(".upload-cont").css("border", "1px dashed black;");
   });
   $(".upload-cont").bind('drop', function (e) {
      var files = e.dataTransfer.files;
      e.preventDefault();
   });
   $("body").bind('drop', function (e) {
      e.preventDefault();
   });
});

In firefox 17,explorer 8 when dragging and dropping a file from desktop into browser the image will be loaded in another page. I had added preventDefault() which works perfectly in chrome. What can be done so that the action is prevented in ff,ie browser.


Solution

  • Try changing the code to be.

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

    The dragover event has to be cancelled also for certain browser to listen to the drop. To quote the mdn

    A listener for the dragenter and dragover events are used to indicate valid drop targets, that is, places where dragged items may be dropped. Most areas of a web page or application are not valid places to drop data. Thus, the default handling for these events is to not allow a drop.

    If you want to allow a drop, you must prevent the default handling by cancelling the event. You can do this either by returning false from an attribute-defined event listener, or by calling the event's event.preventDefault method. The latter may be more feasible in a function defined in a separate script.