Peter-Paul Koch shared valuable insights in an informative tutorial about drag and drop functionality. While working on my own project, I suddenly recalled this resource and decided to quickly put together a demonstration in JSFiddle.
function makeElementDraggable(draggable, container){
// If no container is specified, default to the window
var container = container || window;
var dragging = false;
function handleDrag(moveEvent){
moveEvent.preventDefault();
dragging = true;
var coordinates = [
moveEvent.clientX,
moveEvent.clientY
];
var styleValues = {
position: 'absolute',
left: coordinates[0] + 'px',
top: coordinates[1] + 'px'
};
for(property in styleValues){
if(styleValues.hasOwnProperty(property)){
draggable.style[property] = styleValues[property];
}
}
}
function handleDrop(upEvent){
if(dragging === true){
upEvent.preventDefault();
container.removeEventListener('mousemove', handleDrag, false);
draggable.removeEventListener('mouseup', handleDrop, false);
dragging = false;
}
}
draggable.addEventListener('mousedown', function startDrag(downEvent){
downEvent.preventDefault();
container.addEventListener('mousemove', handleDrag, false);
draggable.addEventListener('mouseup', handleDrop, false);
}, false);
}