PDA

View Full Version : Cross Browser compatible drag/drop


wavsyntax
03-03-2007, 03:11 PM
This drag/drop code will work in IE and FF, and most likely Opera too...

All you have to do is insert the following code in between the <head></head> tags and set any element's class attribute that you'd like to render draggable to "dragdrop".

CSS...

<style type="text/css">
.dragdrop{
position:relative;
cursor:pointer;
}
</style>

Javascript...

<script language="javascript">
var mousedown=false;
var obj=null;
var omx=0;
var omy=0;
var oox=0;
var ooy=0;

function getEvent(e){
if(!e){e=event;}
return e;
}
function getObj(e){
e=getEvent(e);
if(navigator.appName.indexOf("Netscape")!==-1){
return e.target;
}
else{
return e.srcElement;
}
}

document.onmousedown=function(e){
e=getEvent(e);
obj=getObj(e);

if(obj.className!=="dragdrop"){
obj=null;
}
else{
mousedown=true;
omx=e.clientX;
omy=e.clientY;
if(navigator.appName.indexOf("Mozilla")!==-1||navigator.appName.indexOf("Netscape")!==-1){
oox=obj.style.left;
ooy=obj.style.top;
}
else{
oox=obj.style.pixelLeft;
ooy=obj.style.pixelTop;
}
}
}

document.onmouseup=function(e){
obj=null;
mousedown=false;
}

document.onmousemove=function(e){
var e=getEvent(e);
if(mousedown==true){
oox=oox.toString().replace(/px/,"")*1;
ooy=ooy.toString().replace(/px/,"")*1;

obj.style.top=ooy+e.clientY-omy;
obj.style.left=oox+e.clientX-omx;
}
}

</script>


You can preview this script in action here...
preview (http://www.wavsyntax.com/scripts/dragdrop.html)

nexosis
03-15-2007, 03:46 PM
nice script. I like it :)

Actinia
03-16-2007, 04:53 PM
I tried the style and script and it worked fine, until I repositioned the div into a specific location on the page (using Dreamweaver). Then, when I clicked on it, the div leaped back to the origin. Continuing dragging moved the div in parallel with the mouse cursor. A second click and drag (after releasing the mouse button) worked fine.

I used FF2.

John Rostron

the_scyphe
04-03-2007, 03:37 PM
nice script, however is there any way to make the dragging/dropping slower?

the_scyphe