Cancelling HTML5 drag and drop events in web browsers

One has been able drag and drop files in the browser window long time before HTML5 APIs. The bad thing is that the default browser drop action for the files like images is to open them in the current tab i.e. replace the open page contents with the image. This is evil as usually you want to attach files to your email / forum post  / etc. and if you miss few pixels of the drop target zone you usually end up destroying your carefully crafted message instead of appending the next coolest caturday photo.

Here is a quick fix – we set a drop handler on the body which will catch all fall through drop events and cancel them so the browser doesn’t take any action. The trick is that the brain dead drag and drop API wants you to cancel dragover or dragenter event to fire the actual drop event. Remember to re-enable drag and drop events for the actual inputs, like <input type=file> where you want them to be active!

The example code to disable the drop events page wide using jQuery would be:

    /**
     * Make sure if we drop something on the page we don't navigate away
     *
     * Note that you need to catch body dragover and drop event to make this work.
     *
     * https://developer.mozilla.org/En/DragDrop/Drag_Operations#drop
     */
    prepareDontMissDND : function() {

       $(document.body).bind("dragover", function(e) {
            e.preventDefault();
            return false;
       });

       $(document.body).bind("drop", function(e){
            e.preventDefault();
            return false;
        });

    },

\"\" Subscribe to RSS feed Follow me on Twitter Follow me on Facebook Follow me Google+

2 thoughts on “Cancelling HTML5 drag and drop events in web browsers

  1. Maybe a bit later but the question then is, how to re-enable the events on the input’s we want?

  2. Daniel, add a class on those elements and do a check on the drag events. this is what i did

    $(function () {
    $(‘body’).bind(“dragover”, function (e) {
    $(“.supportsDrop”).css(‘background-color’, “red”);

    var dropElement = $(e.target);

    if (dropElement.hasClass(“supportsDrop”)) {
    return true;
    }

    e.preventDefault();
    return false;
    }).bind(“dragleave”, function (e) {
    $(“.supportsDrop”).css(‘background-color’, “blue”);
    }).bind(“drop”, function (e) {
    var dropElement = $(e.target);

    if (dropElement.hasClass(“supportsDrop”)) {
    alert(‘good’);
    return true;
    }

    e.preventDefault();
    return false;
    });
    });

Leave a Reply

Your email address will not be published. Required fields are marked *