Skip to content

Instantly share code, notes, and snippets.

@philfreo
Last active August 17, 2016 18:29
Show Gist options
  • Save philfreo/dc8f2649d0a6bf19545d to your computer and use it in GitHub Desktop.
Save philfreo/dc8f2649d0a6bf19545d to your computer and use it in GitHub Desktop.
Keep track of when a file is currently dragged over a web page
// Keep track of when a file is dragged onto the page.
// Adding a 'filedragging' class to <body> when one is.
(function() {
// Since dragenter & dragleave get fired for children elements, need some workaround
// to tell when file is started & stopped being dragged onto page.
// Ideas extracted from https://github.com/bensmithett/dragster
var klass = 'filedragging',
first = false,
second = false;
$(document).on({
dragenter: function(e) {
if (first) {
second = true;
return;
}
first = true;
// Detect if it's indeed a *file* dragged, versus just some element (e.g. a link) from the page
// http://stackoverflow.com/questions/6848043/how-do-i-detect-a-file-is-being-dragged-rather-than-a-draggable-element-on-my-pa
var dt = e.originalEvent.dataTransfer;
if (dt.types !== null && dt.types.indexOf ? dt.types.indexOf('Files') !== -1 : dt.types.contains('Files')) {
$(document.body).addClass(klass);
}
e.preventDefault();
},
dragleave: function(e) {
if (second) {
second = false;
} else if (first) {
first = false;
}
if (!first && !second) {
$(document.body).removeClass(klass);
}
e.preventDefault();
},
drop: function(e) {
$(document.body).removeClass(klass);
first = second = false;
}
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment