Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 408
TreacleWench Avatar asked Oct 07 '13 11:10

TreacleWench


2 Answers

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!"); }); 
like image 167
Christian Lund Avatar answered Sep 24 '22 09:09

Christian Lund


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;     }); 
like image 24
JimmyBlu Avatar answered Sep 21 '22 09:09

JimmyBlu