Created
July 23, 2020 07:50
-
-
Save av01d/10a526b60749f35546592ecf1e982caa to your computer and use it in GitHub Desktop.
Super simple jQuery file drop plugin
This file contains hidden or 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
/** | |
* Very simple file drop plugin | |
* @author Arjan Haverkamp - webgear.nl | |
* @date 2019-01-21 | |
*/ | |
(function($) { | |
$.fn.FileDropper = function(options) { | |
var settings = $.extend({ | |
// These are the defaults. | |
overSelector: this, | |
overClass: 'over', | |
multiple: false, // Whether or not to accept multiple files | |
onDrop: null, | |
skipClassName: null // Don't do anything when my selector contains this class name | |
}, options); | |
var dragCounter = 0, disabled = false; | |
return this.each(function() { | |
var $this = $(this); | |
$this | |
.on('dragenter', function(e) { | |
if (settings.skipClassName) { | |
disabled = $this.hasClass(settings.skipClassName); | |
if (disabled) { return; } | |
} | |
if (++dragCounter == 1) { | |
//$this.addClass(settings.overClass); | |
$(settings.overSelector).addClass(settings.overClass); | |
} | |
}) | |
.on('dragover', function(e) { | |
if (disabled) { return; } | |
e.preventDefault(); | |
e.originalEvent.dataTransfer.dropEffect = 'copy'; | |
}) | |
.on('dragleave', function(e) { | |
if (disabled) { return; } | |
if (--dragCounter == 0) { | |
//$this.removeClass(settings.overClass); | |
$(settings.overSelector).removeClass(settings.overClass); | |
} | |
}) | |
.on('drop', function(e) { | |
if (disabled) { return; } | |
e.stopPropagation(); | |
e.preventDefault(); | |
//$this.removeClass(settings.overClass); | |
$(settings.overSelector).removeClass(settings.overClass); | |
dragCounter = 0; | |
var files = e.originalEvent.dataTransfer.files; | |
if (files.length == 0 || (!settings.multiple && files.length > 1)) { | |
return; | |
} | |
settings.onDrop && settings.onDrop(!settings.multiple ? files[0] : files); | |
}) | |
}); | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Serving suggestion: