JavaScript Drag and Drop
There are quite a few sources for Javascript Drag and Drop tutorials, most of which have browser compatibility issues. I've tried to compile the simplest and quickest method here, which works in all browsers.
<script type="text/javascript">
var dragElement = 'dragobject' // this is the id of the element you wish to drag
var dropElement = 'dropobject' // this is the id of the element you wish to drop objects onto
var dragObject = null;
var numtasks = document.tasks.elements.length;
var DRAG_lastX, DRAG_lastY;
var DRAG_startX, DRAG_startY;
document.onmousemove = mouseMove;
document.onmouseup = mouseUp;
document.onselectstart = function () { return false; }
for (var i = 0; i < numtasks; i++) {
document.getElementById(dragElement).onmousedown = function() {
dragObject = this;
dragObject.style.position = 'absolute';
DRAG_lastX = 0;
DRAG_lastY = 0;
DRAG_startX = dragObject.style.left;
DRAG_startY = dragObject.style.top;
}
}
}
function mouseMove(ev){
ev = ev || window.event;
var x = ev.pageX ? ev.pageX : ev.x;
var y = ev.pageY ? ev.pageY : ev.y;
if (dragObject != null) {
DRAG_lastX = x + 1;
DRAG_lastY = y + 1;
dragObject.style.left = DRAG_lastX.toString() + 'px';
dragObject.style.top = DRAG_lastY.toString() + 'px';
}
}
function mouseUp(ev){
ev = ev || window.event;
var theTarget = ev.target ? ev.target : ev.srcElement;
if (theTarget.id == dropElement) {
alert('Item Dropped');
}
else {
dragObject.style.left = DRAG_startX;
dragObject.style.top = DRAG_startY;
}
dragObject = null;
}
</script>
Need assistance with your project? Universal Web Services can help.
Contact us to request a quote.