Skip to content

Instantly share code, notes, and snippets.

@kvzhuang
Created February 25, 2013 09:45
Show Gist options
  • Save kvzhuang/5028785 to your computer and use it in GitHub Desktop.
Save kvzhuang/5028785 to your computer and use it in GitHub Desktop.
A CodePen by kvzhuang. JavaScript-DnD - pure JavaScript DnD implementation.
<div class="container">
<div class="draggable">
I am dragable.
</div>
</div>
<div id="drop-area">
Drop area
</div>
var dropArea,
draggable,
getMouseCoords,
getPosition,
mouseOffset;
dropArea = document.getElementById('drop-area');
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;
if (draggable.getAttribute("class") !== "draggable") {
return;
}
mouseOffset = getMouseOffset (draggable, event);
};
document.onmouseup = function (event){
event = event || window.event;
var mousePosition = getMouseCoords(event),
curTarget = dropArea,
targPos = {x: curTarget.offsetLeft, y: curTarget.offsetTop},
targWidth = parseInt(curTarget.offsetWidth),
targHeight = parseInt(curTarget.offsetHeight);
if(
(mousePosition.x > targPos.x) &&
(mousePosition.x < (targPos.x + targWidth)) &&
(mousePosition.y > targPos.y) &&
(mousePosition.y < (targPos.y + targHeight))){
console.log("drop in!");
} else {
console.log("drop out!");
}
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
};
};
.container {
width: 500px;
height: 500px;
border: solid 1px #ddd;
float: left;
}
#drop-area {
width: 500px;
height: 500px;
border: solid 1px #444;
float: left;
}
.draggable {
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