Monday, December 1, 2008

Web-related Drag theory

After vain attemps to realize a good drag method in a web enviorment, i finally understand what i guess is the best way.
A little bit of history :p ...
I started months ago, interested in web dashboard, to implement a dom-drag, i done but it works bad. Sometimes the dragged element "loose the focus" so the mouse pointer go ahead and the element stays back; then when i try to drag it once again it goes away far from mouse :p.
I try in two differents spheres:
Pure DOM-Drag and SVG-Drag (helped by jquery).
Now im gonna tell you my solution..
All is based around 3 javascript events: onmousedown, onmousemove and onmouseup.

This event mean the drag start. Set the elment fired as the event's target; store a variable to true which mean the drag is start. This event should be defined in every draggable elements.

This event mean that the drag is ended. Set the focused element stored with onmousedown to null and to false the variable setted at onmousedown. I think the best is to "bind" this event in the whola document, so if the pointer "goes out" the element this event will be "fired" anyway.

This event is the real drag! This event should be set in the container (maybe the whola document) in which the element is dragged. All you have to do is to set the coordinates of the dragged element (set by onmousedown) to this event's coordinate (if and only if the variable stored in onmousedown is true!).

Onmousedown set the element, tell the "engine" that somthing should be drag, onmousemove get the pointer coordinates and set it as the dragged-element coordinate, onmouseup free all resource and cut off the drag.

Have a nice day!
UPDATE: Pretty Code

var startDrag = false;
var obj = document.getElementById('dragme');
document.onmousemove = function(evt) {
if(startDrag) {
obj.innerHTML = '(' + evt.pageX + ';' + evt.pageY + ')'; = evt.pageX + 'px' = evt.pageY + 'px'

document.onmouseup = function(evt) {
startDrag = false;
obj.innerHTML = 'Drag-me';

obj.onmousedown = function(evt) {
startDrag = true;