PDA

View Full Version : improvement to DOM Drag & Drop script



digitil
08-10-2007, 05:58 PM
http://www.dynamicdrive.com/dynamicindex4/image3.htm

This above script allows the user to drag ANYWHERE inside the DIV.

I have made a small improvement to this script so you can have a draggable handle, which is the only area you can use for dragging - more like what people are used to... the red lines are what I changed.

You have to place a DIV or IMG right after the opening DIV as your handle. See HTML far below.



var dragobject={
z: 0, x: 0, y: 0, offsetx : null, offsety : null, targetobj : null, dragapproved : 0,
initialize:function(){
document.onmousedown=this.drag;
document.onmouseup=function(){this.dragapproved=0}
},
drag:function(e){
var evtobj=window.event? window.event : e;
this.targetobj=window.event? event.srcElement.parentNode : e.target.parentNode;
if (this.targetobj.className=="floatie"){
this.dragapproved=1;
if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0}
if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0}
this.offsetx=parseInt(this.targetobj.style.left);
this.offsety=parseInt(this.targetobj.style.top);
this.x=evtobj.clientX;
this.y=evtobj.clientY;
if (evtobj.preventDefault) evtobj.preventDefault();
document.onmousemove=dragobject.moveit;
}
},
moveit:function(e){
var evtobj=window.event? window.event : e;
if (this.dragapproved==1){
this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px";
this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px";
return false;
}
}
}

dragobject.initialize();


The HTML to use is like this:


<div class="floatie">
<img src="" border=1 width=200 height=20 /><br>
sdfsdfsdf
</div>