TreacleWench
TreacleWench

Reputation: 513

jQuery.on("drop") not firing

I'm trying to implement drag and dropping of files from the desktop the browser window. I have used jQuery to attach three events to the HTML element as in the code below:

$("html").on("dragover", function() {
    $(this).addClass('dragging');
});

$("html").on("dragleave", function() {
    $(this).removeClass('dragging');
});

$("html").on("drop", function(event) {
    event.preventDefault();  
    event.stopPropagation();
    alert("Dropped!");
});

The 'dragover' and 'dragleave' events work fine, displaying an inset border around the entire page when I drag a file over an removing it if I drag the file out again.

However, the 'drop' event doesn't seem to fire at all, the dropped file simply opens in the browser window.

Does anyone have any idea why this event is not firing?

Btw, I am testing this in the latest version of Chrome and using jQuery 1.10.2.

Upvotes: 51

Views: 80942

Answers (3)

Raserad
Raserad

Reputation: 61

You don't need to cancel any event. Just you can user event.preventDefault() for dragover and drop events:

$(document)
.on('dragover', '.target', function (event) {
    event.preventDefault()
    // Do anything you want to do in dragover
})
.on('drop', '.target', function (event) {
    event.preventDefault()
    // You will catch this event here
})

Upvotes: 1

JimmyBlu
JimmyBlu

Reputation: 656

In addition to Christian's solution this can be shortened to:

$('#my-dropzone')
    // crucial for the 'drop' event to fire
    .on('dragover', false) 

    .on('drop', function (e) {
        // do something
        return false;
    });

Upvotes: 26

Christian Lund
Christian Lund

Reputation: 1676

You need to cancel all events

$("html").on("dragover", function(event) {
    event.preventDefault();  
    event.stopPropagation();
    $(this).addClass('dragging');
});

$("html").on("dragleave", function(event) {
    event.preventDefault();  
    event.stopPropagation();
    $(this).removeClass('dragging');
});

$("html").on("drop", function(event) {
    event.preventDefault();  
    event.stopPropagation();
    alert("Dropped!");
});

Upvotes: 125

Related Questions