<HTML>
<HEAD>
<TITLE> Drag n Drop </TITLE>
<style>
.dragme{
position:relative;
border:2px solid #FFFFFF;
width:75px;
font-weight: bold;
font-size:16px;
}
</style>
The style .dragme creates a container around the element which we would like to set as a movable entity in our page except for the position attribute the remaining all are optional and have been added to enhace the visual impact
<script language="JavaScript1.2">
var isIE=document.all;
var isNetscape=document.getElementById&&!document.all;
the above two variable are defined to decide which browser we are working on because the way page elements are accessed differs from IE and Netscape style browsers, both the variable above return an object if it is true else return false.
Eg : if you are in a isIE browser the 'isIE' equals an object and isNetscape is false.
var isdrag=false;
var x,y;
var dragObj;
onMouseMove(Event e) is called when the mouse moves. In order to enable dragging we set a isDrag variable which is set as true when mouse is pressed an reset when it is released.
function onMoveMouse(e)
{
if (isdrag)
{
dragObj.style.left = isNetscape ? tx + e.clientX - x : tx + event.clientX - x;
dragObj.style.top = isNetscape ? ty + e.clientY - y : ty + event.clientY - y;
return false;
}
}
function onMouseDown(e)
{
var dragObj = isNetscape ? e.target : event.srcElement;
var topelement = isNetscape ? "HTML" : "BODY";
while (dragObj.tagName != topelement && dragObj.className != "dragme")
{
dragObj = isNetscape ? dragObj.parentNode : dragObj.parentElement;
}
if (dragObj.className=="dragme")
{
isdrag = true;
dragObj = dragObj;
tx = parseInt(dragObj.style.left+0);
ty = parseInt(dragObj.style.top+0);
x = isNetscape ? e.clientX : event.clientX;
y = isNetscape ? e.clientY : event.clientY;
document.onmousemove=onMoveMouse;
return false;
}
}
document.onmousedown=onMouseDown;
document.onmouseup=new Function("isdrag=false");
</script>
</HEAD>
<BODY>
<div id="div1" class="dragme">Drag this </div>
</BODY>
</HTML>
1 comment:
Very much usable info, easy and crispy. No need for extra search and tiresome trials!.
Post a Comment