Drag & Drop
Download

Drag & Drop by Geoff Lankow is licensed under a Creative Commons Attribution 3.0 License.
This is an extremely flexible drag and drop library. Most importantly it ensures that the mouse coordinates are correct across different browsers. To use it, add custom handlers to the DraggableObject.
Example: drag an element around the screen
This code allows you to place things at any point on the screen. In most cases the tag in question should be a child of document.body, with absolute positioning. If you want to use fixed positioning (ie. the tag stays put if the user scrolls), set d.fixed = true.
var tag = document.getElementById ("tag"); var d = new DraggableObject (tag); d.customMouseMove = function (event) { // dragStart[XY] is position relative to tag at the start of dragging // event.page[XY] is current position, relative to the top left corner of the page var left = event.pageX - this.dragStartX; var top = event.pageY - this.dragStartY; // this.domNode is a reference to tag // this code assumes tag has absolute positioning this.domNode.style.left = left + "px"; this.domNode.style.top = top + "px"; }; d.customMouseUp = function (event) { // this will tell you exactly where the mouse was when you released the button alert ([event.pageX, event.pageY]); };drag me
Example: draw boxes
This code draws a red box over the example code. Note that HTML boxes can't have a negative width, so there's extra code to handle that. Also note that clicking on the code to copy it won't work because of the click handling, so use the button below.
var dragArea = document.getElementById ("dragarea");
var da = new DraggableObject (dragArea);
var current = null;
da.customMouseMove = function (event) {
if (!current) {
current = document.createElement ("div");
current.style.left = this.dragStartX + "px";
current.style.top = this.dragStartY + "px";
dragArea.appendChild (current);
}
var bcr = DraggableObject.fixBCR (dragArea);
var width = event.pageX - bcr.left - this.dragStartX;
var height = event.pageY - bcr.top - this.dragStartY;
current.style.left = (width < 0) ? (this.dragStartX + width) + "px" : this.dragStartX + "px";
current.style.top = (height < 0) ? (this.dragStartY + height) + "px" : this.dragStartY + "px";
current.style.width = Math.abs(width) + "px";
current.style.height = Math.abs(height) + "px";
};
da.customMouseUp = function (event) {
current = null;
};
Extra for experts
If you're creating lots of DraggableObjects, add the mouse handlers to DraggableObject.prototype instead of each object.