Skip to content

Instantly share code, notes, and snippets.

@chipbell4
Last active July 26, 2016 18:24
Show Gist options
  • Save chipbell4/78354196e3175953f121bf5aaab22890 to your computer and use it in GitHub Desktop.
Save chipbell4/78354196e3175953f121bf5aaab22890 to your computer and use it in GitHub Desktop.
Simple Drag and Drop
function makeDraggable(element, onDragMove, onDragEnd) {
element.style.position = 'absolute';
var mouseIsDown = false;
var offset = { x: 0, y: 0};
var oldZIndex = '';
element.addEventListener('mousedown', function(evt) {
oldZIndex = element.style.zIndex;
element.style.zIndex = 999;
var rect = element.getBoundingClientRect();
offset.x = evt.clientX - rect.left;
offset.y = evt.clientY - rect.top;
mouseIsDown = true;
});
element.addEventListener('mousemove', function(evt) {
if(!mouseIsDown) {
return;
}
element.style.left = (evt.clientX - offset.x) + 'px';
element.style.top = (evt.clientY - offset.y) + 'px';
onDragMove instanceof Function ? onDragMove(evt) : null;
});
var finishDrag = function(evt) {
mouseIsDown = false;
element.style.zIndex = oldZIndex;
onDragEnd instanceof Function ? onDragEnd(evt) : null;
}
element.addEventListener('mouseup', finishDrag)
element.addEventListener('mouseout', finishDrag);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment