Monday, January 7, 2008

Drag Drop Essentials

Drag drop of HTML elements (DIV, TABLE, IMG, etc.) could be achieved using the following set of functions found here:
http://www.nofunc.com/Drag_Drop/

Alternatively, you could drop the definition of $(v) and use these subset of functions:


function agent(v) { return(Math.max(navigator.userAgent.toLowerCase().indexOf(v),0)); }
function xy(e,v) {
return(v?(agent('msie')?event.clientY+document.body.scrollTop:e.pageY):(agent('msie')?event.clientX+document.body.scrollTop:e.pageX)); }
function dragOBJ(d,e) {
function drag(e) { if(!stop) { d.style.top=(tX=xy(e,1)+oY-eY+'px'); d.style.left=(tY=xy(e)+oX-eX+'px'); } }

var oX=parseInt(d.style.left),oY=parseInt(d.style.top),eX=xy(e),eY=xy(e,1),tX,tY,stop;
document.onmousemove=drag; document.onmouseup=function(){ stop=1; document.onmousemove=''; document.onmouseup=''; }; }



- As noted you need to attach style="position: relative; top: 0; left: 0;" onmousedown="dragOBJ(this,event); return true;" to the element you wish to drag.

- If your drag div contains input fields you should disable the dragging effect within the input fields. Otherwise, users will loose the ability to select the input field's text with their mouse. So for inout fields you may add the following call to CancelDrag() to disable the dragging that may be inherited from an outer div tag. So you may add an onmousedown event to your input field:

input id="stfName" class="name" type="text" onmousedown="return CancelDrag(event)"
Where CancelDrag() is defined as:

function CancelDrag(A)
{
A.cancelBubble=true;
return true;
}



YUI provides the "draggable" property for dialog boxes that allow you to make a dialog box draggable provided you include that YUI drag-drop .js files:


10
type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/dragdrop/dragdrop-min.js">


However YUI drag-drop .js files may have cause javascript errors when integrated with Virtual Earth 6.0 header files.

To correct the errors you may choose not to use or include the YUI drag drop files and instead rely on the traditional drag-drop functions presented above to make a YUI dialog box draggable. This approach also brings in less code that the YUI drag-drop .js files. The functions above were tested in IE 6, IE 7, FireFox 2.x and Safari 3.0.

No comments: