The DnD extension builds on UsefulJS.Event to provide a simple framework for dragging elements around the page using the mouse or touchscreen.
Registers an element for drag and drop
UsefulJS.DnD.register(elem[, boundingElem[, startCallback[, updateCallback[, ctx]]]])
elem
String|ElementboundingElem
String|Element (optional)elem
is allowed to move; defaults to document.body
startCallback
Function (optional)updateCallback
Function (optional)ctx
Object (optional)Throws TypeError: if elem
is not an element or a
string that resolves to an element.
The start callback function takes has the following form:
startCallback(event, eventSource, registeredElement)
event
will be a mousedown or touchstart event.
eventSource
may well not be the same element that was passed to
register
but registeredElement
will be.
The callback should return the element that is to be dragged; this may not
be the registered element. For example, in a chess game, the elements that are
dragged around may be small images but the element registered for drag events
is a much larger container element allowing pieces to be moved when using a
touchscreen. The callback is also responsible for making the returned element
suitable for dragging (for example, removing the element to be dragged from
its current parent node, adding the element as a child node of the bounding element
and positioning it absolutely). If you want to prevent the drag behaviour (for
example, eventtSource
is not an element that you want to allow
to initiate drag operations) your callback function can return null
.
touches
property in event
. For
example, when using a touch screen you may want to position the drag element
differently so that it is not obscured by the user's finger.If no startCallback
function is supplied, the framework will
use the registered element for dragging and will set style attributes on it
(position: absolute; left, top: the clientX, clientY positions of the event).
The update callback function takes has the following form:
updateCallback(event, x, y, dragElement, complete)
If complete
is true, event
will be a mouseup or touchend event.
Otherwise it will be a mousemove / touchmove event. dragElement
is the element being dragged and x
and y
are the
co-ordinates of its top left corners.
Deregisters an element previously registered for drag-and-drop.
UsefulJS.DnD.deregister(elem)
elem
String|ElementThrows TypeError: if elem
is not an element or a
string that resolves to an element.
Removes event handlers that were added to elem
by the
UsefulJS.DnD.register
call.
Gets the x- and y-offsets of one element from another
UsefulJS.DnD.elementOffset(elem[, eRel])
elem
String|ElementeRel
String|Element (optional)Returns Array: the x and y co-ordinates of elem
relative
to eRel.
Throws TypeError: if elem
is not an element or a
string that resolves to an element.