Monday, December 26, 2011

Javascript to Move a DIV around (non-touchscreen version)

Ever wonder how to use javascript to move a DIV around your web page? This fascinated me because it is so cool to make your web page to have the drag-and-drop feature.

The trick is to use the onmousemove event listener on the body level. Here are the codes:




<html>
<head>
<script type="text/javascript">
var PositionFlag = 0;
var p1;
var p2;
var p3;
var p4;
var pos_x;
var pos_y;
var diff_x;
var diff_y;
var mouse_x;
var mouse_y;
var once = 0;

function UpdateXY()
{
mouse_x = window.event.clientX;
mouse_y = window.event.clientY;
p1 = 'Mouse: X=' + mouse_x + ' Y=' + mouse_y ;
document.getElementById('coorinfo1').innerText = p1;

box_x = document.getElementById('myBox').offsetLeft;
box_y = document.getElementById('myBox').offsetTop;

p2 = 'myBox: X=' + box_x + ' Y=' + box_y ;
document.getElementById('coorinfo2').innerText = p2;

if (once == 0) {
diff_x = mouse_x - box_x;
diff_y = mouse_y - box_y;

}

p3 = 'Diff : X=' + diff_x + ' Y=' + diff_y ;
document.getElementById('coorinfo3').innerText = p3;

if (PositionFlag == 1) {
x = mouse_x - diff_x;
y = mouse_y - diff_y;

p4 = 'Diff : X=' + x + ' Y=' + y ;
document.getElementById('coorinfo4').innerText = p4;

document.getElementById('myBox').style.left = x;
document.getElementById('myBox').style.top = y;

once = 1;
}

}

</script></head>

<div id="myBox" style="position:absolute;z-index:100;" onmousedown="PositionFlag=1;" onmouseup="PositionFlag=0;once=0;"><table border=1><tr><td bgcolor=#ddeeff align=center><br>  <font color=orange>orange</font>  <br><br></td></tr></table></div>

<body onmousemove="UpdateXY()" onload="document.getElementById('myBox').style.cursor = 'hand';document.body.style.cursor = 'crosshair';document.getElementById('myBox').style.left=100;document.getElementById('myBox').style.top=100;">
<div id="coorinfo1"></div>
<div id="coorinfo2"></div>
<div id="coorinfo3"></div>
<div id="coorinfo4"></div>



</body>
</html>





You will see the XY coordinates displayed with a DIV box with the text orange on it. Simply drag the box around and you'll see the magic.

Let me know if you have any questions regarding the codes as I put very little comments on it. Sorry. Too rush. Gotta go.

No comments:

Post a Comment