Drag blue in box
by Sasá Rafalsky
HTML
<div id='container' style="width: 400px;height: 400px;">
<div id="elem" onmousedown='mydragg.startMoving(this,event);' onmouseup='mydragg.stopMoving();' style="width: 100px;height: 36px;">
</div>
</div>
<script>
var mydragg = function(){
return {
move : function(divid,xpos,ypos){
divid.style.left = xpos + 'px';
divid.style.top = ypos + 'px';
},
startMoving : function(divid,evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
divTop = divid.style.top,
divLeft = divid.style.left,
eWi = parseInt(divid.style.width),
eHe = parseInt(divid.style.height),
cWi = parseInt(document.getElementById("container").style.width),
cHe = parseInt(document.getElementById("container").style.height);
document.getElementById("container").style.cursor='move';
divTop = divTop.replace('px','');
divLeft = divLeft.replace('px','');
var diffX = posX - divLeft,
diffY = posY - divTop;
document.onmousemove = function(evt){
evt = evt || window.event;
var posX = evt.clientX,
posY = evt.clientY,
aX = posX - diffX,
aY = posY - diffY;
if (aX < 0) aX = 0;
if (aY < 0) aY = 0;
if (aX + eWi > cWi) aX = cWi - eWi;
if (aY + eHe > cHe) aY = cHe -eHe;
mydragg.move(divid,aX,aY);
}
},
stopMoving : function(){
document.onmousemove = function(){}
},
}
}();
</script>
CSS
#container {
position:absolute;
background-color: #404040;
height: 400px;
width: 400px;
margin: 50px;
}
#elem{
cursor: pointer;
position: absolute;
background-color: #09f;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
width: 100px;
height: 36px;
border-radius: 3px;
}
JavaScript
// --> http://jsfiddle.net/g6m5t8co/11/