11 August, 2007

HowTo move objects within the html page via JavaScript

For one of my web projects I created universal JavaScript for moving any objects within the page. This is my simple Drag and Drop implementation.
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.

1 comment:

Anonymous said...

Hello, i found some code on your page, but it doesn't work with even loose.dtd . I tried to fix it, but I failed. Do You have an updated version or can give some directions how to fix it? Or maybe it's impossible to work under any dtd?
I mean that when i put that line:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

as a first line in the document, it stops working.

I hope You will read this comment and post an answer. I'll return to that page in some time.

Kind regards,
anonim ;)