Monday, January 18, 2010

How to Create Draggable Div

JavaScript can be used to create draggable item or Div on web page. How to create draggable div / Layer in javascript.

<style>
<!--
.dragmeit{position:relative;}
-->
</style>
<script language="JavaScript1.2">
<!--

var ie = document.all;
var nn6 = document.getElementById&&!document.all;

var isdraggingnow = false;
var x,y;
var myobj;

function movemousenow(e)
{
if (isdraggingnow)
{
myobj.style.left = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
myobj.style.top = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
return false;
}
}

function selectmousenow(e)
{
var firstobj = nn6 ? e.target : event.srcElement;
var topelement = nn6 ? "HTML" : "BODY";

while (firstobj.tagName != topelement && firstobj.className != "dragmeit")
{
firstobj = nn6 ? firstobj.parentNode : firstobj.parentElement;
}

if (firstobj.className=="dragmeit")
{
isdraggingnow = true;
myobj = firstobj;
tx = parseInt(myobj.style.left+0);
ty = parseInt(myobj.style.top+0);
x = nn6 ? e.clientX : event.clientX;
y = nn6 ? e.clientY : event.clientY;
document.onmousemove=movemousenow;
return false;
}
}

document.onmousedown=selectmousenow;
document.onmouseup=new Function("isdraggingnow=false");

function hideDivs()
{
var arr = document.getElementsByTagName('div')
for(var i=0; i<arr.length;i++)
{
arr[i].style.display = (arr[i].style.display == 'block')? 'none':'block';
}
}

//-->
</script>

<a href="#" onclick="hideDivs();return false;"><font face="arial" size="2" ><b>Hide/Show</b></font></a>

<div >
<img src="yourimage.gif" class="dragmeit">

</div>

No comments:

Post a Comment