Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Created July 8, 2016 23:49
Show Gist options
  • Save jbuncle/f66c9c5ecc7b831541d7b5d3e668b6fc to your computer and use it in GitHub Desktop.
Save jbuncle/f66c9c5ecc7b831541d7b5d3e668b6fc to your computer and use it in GitHub Desktop.
jQuery Drag and Drop
$.fn.dragAndDrop = function ($to, callback) {
// 'this' is the element to be dragged.
var $from = $(this);
// Make draggable
$from.attr('draggable', 'true');
// Enable dragging over '$to'
$to.on('dragover', function (event) {
if ($from.has(event.currentTarget)) {
// Allow drag onto '$to' elements
event.preventDefault();
}
});
// Handle the drop
$to.on('drop', function (event) {
event.preventDefault();
var $droppedOnto = $(event.currentTarget);
var $beingDropped = $(event.target);
// Invoke the callback, passing in the elements
callback($beingDropped, $droppedOnto);
});
return this;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment