Last active
August 17, 2016 18:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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