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.
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!");
});
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;
});