Created
February 25, 2013 03:41
-
-
Save kvzhuang/5027350 to your computer and use it in GitHub Desktop.
A CodePen by kvzhuang. JavaScript-DnD - pure JavaScript DnD implementation.
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
<div class="container"> | |
<div class="dragable"> | |
I am dragable. | |
</div> | |
</div> |
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
var draggable, | |
getMouseCoords, | |
mouseOffset; | |
document.onmousemove = function (event) { | |
event = event || window.event; | |
var mousePosition = getMouseCoords(event); | |
if (draggable){ | |
draggable.style.position = 'absolute'; | |
draggable.style.top = mousePosition.y - mouseOffset.y + "px"; | |
draggable.style.left = mousePosition.x - mouseOffset.x + "px"; | |
console.log(mousePosition); | |
return false; | |
} | |
}; | |
document.onmousedown = function (event) { | |
event = event || window.event; | |
draggable = event.target || event.srcElement; | |
mouseOffset = getMouseOffset (draggable, event); | |
}; | |
document.onmouseup = function (event){ | |
draggable = null; | |
} | |
getMouseCoords = function (event) { | |
if (event.pageX || event.pageY) { | |
return {x: event.pageX, y: event.pageY}; | |
} | |
return { | |
x: event.clientX + document.body.scrollLeft - document.body.clientLeft, | |
y: event.clientY + document.body.scrollTop - document.body.clientTop | |
} | |
}; | |
getMouseOffset = function (target, event) { | |
event = event || window.event; | |
var mousePosition = getMouseCoords(event); | |
var left = target.offsetLeft, top = target.offsetTop;; | |
var documentPosition = {x: left, y: top}; | |
return { | |
x: mousePosition.x - documentPosition.x, | |
y: mousePosition.y - documentPosition.y | |
}; | |
} |
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
.container { | |
width: 500px; | |
height: 500px; | |
border: solid 1px #ddd; | |
} | |
.dragable { | |
border: solid 1px #000; | |
width: 200px; | |
cursor: move; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment