Sunday, June 11, 2006

Drag n Drop in JavaScript

With Drag n Drop becoming so frequently used in web application these days, i found an article in http://www.javascriptkit.com very usefull.

I have implemented same in my blog. You can Drag the Title of my blog around and rearrange it as you wish. I used following bit of code from above mentioned site for the same.

This code along with little bit of AJAX can really give very pleasing results.



Create Following in your Css File
--------------------------------------

.drag{position:relative;cursor:hand;z-index:5}


Drag Drop Code Starts Here-
------------------
var dragapproved=false
var z,x,y
function move()
{
if (event.button==1&&dragapproved)
{
z.style.pixelLeft=temp1+event.clientX-x;
z.style.pixelTop=temp2+event.clientY-y;
return false
}
}
function drags()
{
if (!document.all)
return
if (event.srcElement.className=="drag")
{
dragapproved=true
z=event.srcElement
temp1=z.style.pixelLeft
temp2=z.style.pixelTop
x=event.clientX
y=event.clientY
document.onmousemove=move
}
}
document.onmousedown=drags
document.onmouseup=new Function("dragapproved=false")

Code Ends
------