Last active
July 26, 2016 18:24
-
-
Save chipbell4/78354196e3175953f121bf5aaab22890 to your computer and use it in GitHub Desktop.
Simple Drag and Drop
This file contains 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
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