-->
Bookmark and Share

Generic Drag

See the demo page for the finished version of the code.

Performing the Drag

The dragGo() function will now be called anytime the mouse moves. Like dragStart(), it calculates the current mouse position relative to the page.

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

Subtracting the starting mouse coordinates from these gives the distance (in pixels) and direction the mouse has moved both horizontally and vertically. Adding these differences to the element's starting position gives the new position for the element.

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left =
    (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  =
    (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

So the element's left and top style values are changed accordingly, making the element appear to move with the mouse pointer.

The last step is to again stop the event flow and cancel any default action for it.

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();

Ending the Drag

When the user releases the mouse button, dragStop() is called. All this function does is remove the capturing of the mousemove and mouseup events from the page.

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

So now dragGo() will no longer be called in response to mouse movements, until a new drag is started.

Conclusion

There you have it, a simple way to add user interaction to a page. Although browser incompatibilities - mostly due to Internet Explorer's proprietary event model - create the need for additional code, the approach is relatively straightforward.