Currently I'm engaged with implementing a Drag and Drop GUI. I've discovered that there a not many resources (tutorials, etc.) available. So I wrote this:
function Cursor(cssSelector, rightLimit, bottomLimit) {
var element = document.querySelector('#square');
var styles = window.getComputedStyle(square);
var x = 0;
var y = 0;
var fromLeft = 0;
var fromTop = 0;
var pushed = false;
var limits = {
top: 0,
right: rightLimit,
bottom: bottomLimit,
left: 0
}
// Uses the offsetX and the offsetY of the
// mousedown event.
this.setCoordinates = function(left, top) {
if (!fromLeft && !fromTop) {
fromLeft = left;
fromTop = top;
}
}
this.togglePushed = function() {
pushed ? pushed = false : pushed = true;
}
this.getPushed = function() {
return pushed;
}
// Uses the offsetX and the offsetY of the
// mousemove event.
this.moveCursor = function(offsetX, offsetY) {
// How much have the x and the y coordinate
// changed since the mousedown event?
var tmpX = offsetX - fromLeft;
var tmpY = offsetY - fromTop;
if ((x + tmpX) <= limits.right && (x + tmpX) >= limits.left &&
(y + tmpY) >= limits.top && (y + tmpY) <= limits.bottom) {
// If the values are valid then store them ...
x += tmpX;
y += tmpY;
// ... and use them to move the element.
element.style.left = x + 'px';
element.style.top = y + 'px';
}
}
}
var cursor = new Cursor('#square', 550, 450);
square.addEventListener('mousedown', function(ev) {
cursor.togglePushed();
cursor.setCoordinates(ev.offsetX, ev.offsetY);
});
document.body.addEventListener('mouseup', function(ev) {
cursor.togglePushed();
});
square.addEventListener('mousemove', function(ev) {
if (cursor.getPushed()) {
cursor.moveCursor(ev.offsetX, ev.offsetY);
}
});
body {
background-color: #eefafa;
}
#wrap {
width: 600px;
margin: 50px auto;
}
#panel {
height: 500px;
position: relative;
background-color: rgba(150, 150, 150, 0.2);
border-radius: 3px;
}
#square {
width: 50px;
height: 50px;
background-color: orangered;
border: 1px solid teal;
border-radius: 3px;
position: absolute;
top: 0px;
left: 0px;
}
.instruct {
font-size: 125%;
font-weight: bold;
font-family: helvetica;
}
<div id="wrap">
<p class="instruct">
Click the square. Keep the mouse-button pushed and
move the pointer slowly.
</p>
<div id="panel">
<div id="square"></div>
</div>
</div>
There's also a demo on CodePen.
pushed ? pushed = false : pushed = true;
can be simplified:pushed = !pushed;
\$\endgroup\$