I'm publishing this source. I think, it will be illustrative and useful example.
This screenshot shows how to this script works.
<html>
<body>
<style type="text/css">
.movable {
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
cursor:pointer;
border:solid 1px gray;
}
</style>
<script type="text/javascript">
var posx;
var posy;
var zMax = 0;
var obj;
function drag_start(itemToMove, e)
{
itemToMove.style.zIndex = ++window.zMax;
if (!e) e = window.event;
obj = itemToMove;
posx = e.clientX - parseInt(obj.style.left);
posy = e.clientY - parseInt(obj.style.top);
itemToMove.style.cursor="move";
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
function drag_stop(e)
{
if (obj) {
obj.style.cursor="pointer";
obj = null;
}
}
function drag(e)
{
if (!obj) return;
if (!e) e = window.event;
var height, width;
if (document.all)
{
height = document.body.offsetHeight;
width = document.body.offsetWidth;
}
else if (document.layers)
{
height = window.innerHeight;
width = window.innerWidth;
}
var newX = e.clientX - posx;
var newY = e.clientY - posy;
if (newX < -obj.clientWidth / 2)
{
newX = -obj.clientWidth / 2;
posx = e.clientX - parseInt(obj.style.left);
}
if (newY < -obj.clientHeight / 2)
{
newY = -obj.clientHeight / 2;
posy = e.clientY - parseInt(obj.style.top);
}
obj.style.left = newX;
obj.style.top = newY;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
document.onmousemove = drag;
document.onmouseup = drag_stop;
document.ondragstart = function()
{
return false;
}
document.onselectstart = function()
{
return false;
}
</script>
<div class="movable" style="left:100px; top:100px;" onmousedown="drag_start(this,event)"></div>
<div class="movable" style="left:200px; top:200px;" onmousedown="drag_start(this,event)"></div>
</body>
</html>
E.g.: I used this script in my Online Ruler.
You may see how it works, see in action.