Last active
August 29, 2015 14:15
-
-
Save keithshep/5ad01aa7ca87bf960ef3 to your computer and use it in GitHub Desktop.
some code to simplify file drag-and-drop implementation in JavaScript
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
/** | |
* This callback will be called with the file that was dropped. | |
* @callback dropCallback | |
* @param file the file object | |
*/ | |
/** | |
* Create a file drop area | |
* @param activeElement | |
* the element that the user can drop on to trigger a callback | |
* @param highlightElement | |
* the element that we will overlay with the hover message when the | |
* user drags a file over | |
* @param hoverMessage {string} | |
* the text to use in the drop overlay | |
* @param dropCallback {dropCallback} | |
*/ | |
function fileDropify(activeElement, highlightElement, hoverMessage, dropCallback) { | |
var fileDropOverlay = null; | |
var designDropActive = function() { | |
if(fileDropOverlay == null) { | |
var offset = highlightElement.offset(); | |
fileDropOverlay = $(document.createElement('div')); | |
fileDropOverlay.css(offset); | |
fileDropOverlay.width(highlightElement.outerWidth()); | |
fileDropOverlay.height(highlightElement.outerHeight()); | |
fileDropOverlay.addClass('file-drop-panel'); | |
var textSpan = $(document.createElement('span')); | |
textSpan.text(hoverMessage); | |
fileDropOverlay.append(textSpan); | |
$('body').append(fileDropOverlay); | |
} | |
}; | |
var designDropInactive = function() { | |
if(fileDropOverlay !== null) { | |
fileDropOverlay.remove(); | |
fileDropOverlay = null; | |
} | |
}; | |
activeElement.on('dragenter', function(e) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
designDropActive(); | |
}); | |
activeElement.on('dragover', function(e) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
designDropActive(); | |
}); | |
activeElement.on('dragleave', function(e) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
designDropInactive(); | |
}); | |
activeElement.on('drop', function(e) { | |
e.preventDefault(); | |
e.stopPropagation(); | |
designDropInactive(); | |
var files = e.originalEvent.dataTransfer.files; | |
if(files.length === 1) { | |
dropCallback(files[0]); | |
} | |
}); | |
} | |
/* | |
The following CSS classes give a reasonable starting point | |
for styling the drag and drop overlay panel | |
.file-drop-panel { | |
display: table; | |
position: absolute; | |
background-color: rgba(255, 255, 255, 0.75); | |
pointer-events: none; | |
border: 5px dashed gray; | |
font-family: sans-serif; | |
font-size: 3em; | |
color: gray; | |
} | |
.file-drop-panel > span { | |
display: table-cell; | |
vertical-align: middle; | |
text-align: center; | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment