Created
July 17, 2015 13:57
-
-
Save dux/d34e1142750a540380c3 to your computer and use it in GitHub Desktop.
Simple native + jQuery drag and drop
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Native drag drop</title> | |
</head> | |
<body> | |
<style media="screen"> | |
div.elms .item { width:100px; border:1px solid #ddd; background:#eee; padding:5px; margin-bottom:5px; } | |
div.targets { margin-top:100px; } | |
div.targets .target { width:100px; height:50px; border:1px solid #ddd; background:#eee; padding:5px; margin-bottom:5px; } | |
#info { top:20px; right:46%; padding:5px 10px; background-color:#eee; position:absolute; } | |
</style> | |
<div id="info">...</div> | |
<div class="elms"> | |
<div class="item draggable">Item 1</div> | |
<div class="item draggable">Item 2</div> | |
<div class="item draggable">Item 3</div> | |
</div> | |
<div class="targets"> | |
<div class="target" data-ondrop="DragDrop.drop_resolve">Target a</div> | |
<div class="target" data-ondrop="DragDrop.drop_resolve">Target b</div> | |
<div class="target" data-ondrop="DragDrop.drop_resolve">Target c</div> | |
</div> | |
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> | |
<script> | |
'use strict'; | |
window.DragDrop = { | |
_on_drop: function(ev, func) { | |
ev.preventDefault(); | |
func(window.drag_source, ev.target); | |
delete window.drag_source; | |
}, | |
init: function() { | |
$('.draggable').each(function() { | |
if (! this.getAttribute('draggable')) { | |
this.setAttribute('draggable', 'true'); | |
this.setAttribute('ondragstart', 'window.drag_source = event.target;'); | |
} | |
}) | |
$('*[data-ondrop]').each(function() { | |
var func_name = this.getAttribute('data-ondrop'); | |
this.setAttribute('ondrop', 'DragDrop._on_drop(event, '+func_name+')'); | |
this.setAttribute('ondragover', 'event.preventDefault()'); | |
}) | |
} | |
}; | |
// <div class="item draggable">Item 1</div> | |
// <div class="target" data-ondrop="DragDrop.drop_resolve">Target a</div> | |
window.alert = function(data) { $('#info').html(data); } | |
DragDrop.drop_resolve = function(source, target) { | |
alert('Drop: '+source.innerHTML+' in '+target.innerHTML); | |
} | |
DragDrop.init(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment