PDA

View Full Version : JS Drag and drop...



boarderstu
12-01-2007, 03:09 PM
Hi Guys!

I'm trying to implement a drag and drop functionality to my site to which I followed a tutorial where it works fine..

But for me it doesn't...

I am adding DIV tags thru the DOM and thats fine, but when I drag them.. they just don't.

The site can be viewed here:

http://www.sasklinar.co.uk/tb/

with the script posted below..


// JavaScript Document
// JavaScript Document



function newdiv(){
var div;

div = document.createElement("div");

div.innerHTML = 'drag me..';

div.style.backgroundColor = "#0099FF";
div.style.borderStyle = "solid";
div.className = "drag";
document.body.appendChild (div);

}


var _startX = 0;
var _startY = 0;

var _offsetY = 0;
var _offsetX = 0;

var _dragElement; //pass from OnMouseDown to OnMoveMove

var _oldZIndex = 0; //we increase the Z while moving..

var _debug = $('debug');



InitDragDrop();

function InitDragDrop()
{

document.onmouseDown = OnMouseDown;
document.onmouseup = OnMouseUp;

}
function OnMouseDown (e)
{

if (e ==null){
e = window.event;
}
var target = e.target != null ? e.target : e.srcElement;

//for IE, left click == 1
//FF ==2


_debug.innerHTML = target.className == 'drag' ? 'draggable element clicked' : 'NON-draggable element clicked';

if((e.button == 1 && window.event != null || e.button == 0) && target.className == 'drag')
{

//get the mouse position

_startX = e.clientX;
_startY = e.clientY;

//get the elements clicked position

_offsetX = target.style.left;
_offsetY = target.style.top;

//get set the ZIndex

_oldZIndex = target.style.zindex;

target.style.zindex = 10000;

_dragElement = target;

document.onmousemove = OnMouseMove;

//cancel any text selections
document.body.focus();

//prevent text selection in IE

document.onselectstart = function () {return false;};

//prevent any text selection (not IE)

return false;

}
}

function OnMouseMove(e)
{

if(e ==null)
{
var e = window.event;
}

//this is the actual drag...

_dragElement.style.left = (_offsetX + e.clientX - startX) + 'px';
_dragElement.style.left = (_offsetY + e.clientY - startY) + 'px';

_debug.innerHTML = '(' + _dragElement.style.left + ', ' + _dragElement.style.top + ')';


}

function OnMouseUp(e)
{

if(_dragElement != null)
{

_dragElement.style.zIndex = _oldZIndex;

//were done with this till the next mouse down...

document.onmousemove = null;
document.onselectstart = null;

//this is how we know were not dragging..

_dragElement = null;
}
}

function $(id) { return document.getElementById(id); }