Friday, December 02, 2005

javascript Drag

Have you seen cool drag&drop features in some websites, with which you can dynamicly arrange web contents? If not, check out google personal or msn space.

It turns out not that difficult to implement your own drag and drop. Below is a very lightweight and customizable web Drag&Drop support using javascript and dhtml. Supports both IE and Firefox.

<script type="text/javascript">
  function getEvent(e) {
  return e ? e : window.event;
}

function moveElem(elem, left, top) {
  var style = elem.style;
  style.left = left;
  style.top = top;
}

function Drag(elem) {
  var self = this;
  this.elem = elem;

  elem.onmousedown = function(e) {
    e = getEvent(e);
    self.onBeginDrag(e.clientX, e.clientY);
    saveLast(e.clientX, e.clientY);
    document.onmousemove = onmousemove;
    document.onmouseup = onmouseup;
    return false;
  }

  function onmousemove(e) {
    e = getEvent(e);
    self.onDrag(e.clientX, e.clientY);
    saveLast(e.clientX, e.clientY);
    return false;
  }

  function onmouseup(e) {
    e = getEvent(e);
    document.onmousemove = null;
    document.onmouseup = null;
    self.onEndDrag(e.clientX, e.clientY);
    return false;
  }

  function saveLast(x, y) {
    self.x0 = x;
    self.y0 = y;
  }
}

Drag.prototype.move = function(dx, dy) {
  var style = this.elem.style;
  var x = parseInt(style.left);
  var y = parseInt(style.top);
  style.left = x + dx;
  style.top = y + dy;
}

Drag.prototype.moveTo = function(x, y) {
  moveElem(this.elem, x, y);
}

Drag.prototype.drag = function(x, y) {
  this.move(x - this.x0, y - this.y0);
}

Drag.prototype.onDrag = function(x, y) {
  this.drag(x, y);
}

Drag.prototype.onBeginDrag = function(x, y) {}
Drag.prototype.onEndDrag = function(x, y) {}
</script>


To make an element draggable, simply call "new Drag(elem)" for the element, e.g.,

<img id="dragimg" src="...">
<script type="text/javascript">
  new Drag(document.getElementById("dragimg"));
</script>

1 comment:

Joe said...

COOL! Good job