2 Copyright (c) 2006, Yahoo! Inc. All rights reserved.
3 Code licensed under the BSD License:
4 http://developer.yahoo.net/yui/license.txt
9 var Event=YAHOO.util.Event;
10 var Dom=YAHOO.util.Dom;
13 * Defines the interface and base operation of items that that can be
14 * dragged or can be drop targets. It was designed to be extended, overriding
15 * the event handlers for startDrag, onDrag, onDragOver, onDragOut.
16 * Up to three html elements can be associated with a DragDrop instance:
18 * <li>linked element: the element that is passed into the constructor.
19 * This is the element which defines the boundaries for interaction with
20 * other DragDrop objects.</li>
21 * <li>handle element(s): The drag operation only occurs if the element that
22 * was clicked matches a handle element. By default this is the linked
23 * element, but there are times that you will want only a portion of the
24 * linked element to initiate the drag operation, and the setHandleElId()
25 * method provides a way to define this.</li>
26 * <li>drag element: this represents an the element that would be moved along
27 * with the cursor during a drag operation. By default, this is the linked
28 * element itself as in {@link YAHOO.util.DD}. setDragElId() lets you define
29 * a separate element that would be moved, as in {@link YAHOO.util.DDProxy}
32 * This class should not be instantiated until the onload event to ensure that
33 * the associated elements are available.
34 * The following would define a DragDrop obj that would interact with any
35 * other DragDrop obj in the "group1" group:
37 * dd = new YAHOO.util.DragDrop("div1", "group1");
39 * Since none of the event handlers have been implemented, nothing would
40 * actually happen if you were to run the code above. Normally you would
41 * override this class or one of the default implementations, but you can
42 * also override the methods you want on an instance of the class...
44 * dd.onDragDrop = function(e, id) {
45 * alert("dd was dropped on " + id);
48 * @namespace YAHOO.util
51 * @param {String} id of the element that is linked to this instance
52 * @param {String} sGroup the group of related DragDrop objects
53 * @param {object} config an object containing configurable attributes
54 * Valid properties for DragDrop:
55 * padding, isTarget, maintainOffset, primaryButtonOnly,
57 YAHOO.util.DragDrop = function(id, sGroup, config) {
59 this.init(id, sGroup, config);
63 YAHOO.util.DragDrop.prototype = {
66 * The id of the element associated with this object. This is what we
67 * refer to as the "linked element" because the size and position of
68 * this element is used to determine when the drag and drop objects have
76 * Configuration attributes passed into the constructor
83 * The id of the element that will be dragged. By default this is same
84 * as the linked element , but could be changed to another element. Ex:
93 * the id of the element that initiates the drag operation. By default
94 * this is the linked element, but could be changed to be a child of this
95 * element. This lets us do things like only starting the drag when the
96 * header element within the linked html element is clicked.
97 * @property handleElId
104 * An associative array of HTML tags that will be ignored if clicked.
105 * @property invalidHandleTypes
106 * @type {string: string}
108 invalidHandleTypes: null,
111 * An associative array of ids for elements that will be ignored if clicked
112 * @property invalidHandleIds
113 * @type {string: string}
115 invalidHandleIds: null,
118 * An indexted array of css class names for elements that will be ignored
120 * @property invalidHandleClasses
123 invalidHandleClasses: null,
126 * The linked element's absolute X position at the time the drag was
128 * @property startPageX
135 * The linked element's absolute X position at the time the drag was
137 * @property startPageY
144 * The group defines a logical collection of DragDrop objects that are
145 * related. Instances only get events when interacting with other
146 * DragDrop object in the same group. This lets us define multiple
147 * groups using a single DragDrop subclass if we want.
149 * @type {string: string}
154 * Individual drag/drop instances can be locked. This will prevent
155 * onmousedown start drag.
166 lock: function() { this.locked = true; },
169 * Unlock this instace
172 unlock: function() { this.locked = false; },
175 * By default, all insances can be a drop target. This can be disabled by
176 * setting isTarget to false.
183 * The padding configured for this drag and drop object for calculating
184 * the drop zone intersection with this object.
191 * Cached reference to the linked element
198 * Internal typeof flag
199 * @property __ygDragDrop
205 * Set to true when horizontal contraints are applied
206 * @property constrainX
213 * Set to true when vertical contraints are applied
214 * @property constrainY
221 * The left constraint
229 * The right constraint
246 * The down constraint
254 * Maintain offsets when we resetconstraints. Set to true when you want
255 * the position of the element relative to its parent to stay the same
256 * when the page changes
258 * @property maintainOffset
261 maintainOffset: false,
264 * Array of pixel locations the element will snap to if we specified a
265 * horizontal graduation/interval. This array is generated automatically
266 * when you define a tick interval.
273 * Array of pixel locations the element will snap to if we specified a
274 * vertical graduation/interval. This array is generated automatically
275 * when you define a tick interval.
282 * By default the drag and drop instance will only respond to the primary
283 * button click (left button for a right-handed mouse). Set to true to
284 * allow drag and drop to start with any mouse click that is propogated
286 * @property primaryButtonOnly
289 primaryButtonOnly: true,
292 * The availabe property is false until the linked dom element is accessible.
293 * @property available
299 * By default, drags can only be initiated if the mousedown occurs in the
300 * region the linked element is. This is done in part to work around a
301 * bug in some browsers that mis-report the mousedown if the previous
302 * mouseup happened outside of the window. This property is set to true
303 * if outer handles are defined.
305 * @property hasOuterHandles
309 hasOuterHandles: false,
312 * Code that executes immediately before the startDrag event
313 * @method b4StartDrag
316 b4StartDrag: function(x, y) { },
319 * Abstract method called after a drag/drop object is clicked
320 * and the drag or mousedown time thresholds have beeen met.
322 * @param {int} X click location
323 * @param {int} Y click location
325 startDrag: function(x, y) { /* override this */ },
328 * Code that executes immediately before the onDrag event
332 b4Drag: function(e) { },
335 * Abstract method called during the onMouseMove event while dragging an
338 * @param {Event} e the mousemove event
340 onDrag: function(e) { /* override this */ },
343 * Abstract method called when this element fist begins hovering over
344 * another DragDrop obj
345 * @method onDragEnter
346 * @param {Event} e the mousemove event
347 * @param {String|DragDrop[]} id In POINT mode, the element
348 * id this is hovering over. In INTERSECT mode, an array of one or more
349 * dragdrop items being hovered over.
351 onDragEnter: function(e, id) { /* override this */ },
354 * Code that executes immediately before the onDragOver event
358 b4DragOver: function(e) { },
361 * Abstract method called when this element is hovering over another
364 * @param {Event} e the mousemove event
365 * @param {String|DragDrop[]} id In POINT mode, the element
366 * id this is hovering over. In INTERSECT mode, an array of dd items
367 * being hovered over.
369 onDragOver: function(e, id) { /* override this */ },
372 * Code that executes immediately before the onDragOut event
376 b4DragOut: function(e) { },
379 * Abstract method called when we are no longer hovering over an element
381 * @param {Event} e the mousemove event
382 * @param {String|DragDrop[]} id In POINT mode, the element
383 * id this was hovering over. In INTERSECT mode, an array of dd items
384 * that the mouse is no longer over.
386 onDragOut: function(e, id) { /* override this */ },
389 * Code that executes immediately before the onDragDrop event
393 b4DragDrop: function(e) { },
396 * Abstract method called when this item is dropped on another DragDrop
399 * @param {Event} e the mouseup event
400 * @param {String|DragDrop[]} id In POINT mode, the element
401 * id this was dropped on. In INTERSECT mode, an array of dd items this
404 onDragDrop: function(e, id) { /* override this */ },
407 * Abstract method called when this item is dropped on an area with no
409 * @method onInvalidDrop
410 * @param {Event} e the mouseup event
412 onInvalidDrop: function(e) { /* override this */ },
415 * Code that executes immediately before the endDrag event
419 b4EndDrag: function(e) { },
422 * Fired when we are done dragging the object
424 * @param {Event} e the mouseup event
426 endDrag: function(e) { /* override this */ },
429 * Code executed immediately before the onMouseDown event
430 * @method b4MouseDown
431 * @param {Event} e the mousedown event
434 b4MouseDown: function(e) { },
437 * Event handler that fires when a drag/drop obj gets a mousedown
438 * @method onMouseDown
439 * @param {Event} e the mousedown event
441 onMouseDown: function(e) { /* override this */ },
444 * Event handler that fires when a drag/drop obj gets a mouseup
446 * @param {Event} e the mouseup event
448 onMouseUp: function(e) { /* override this */ },
451 * Override the onAvailable method to do what is needed after the initial
452 * position was determined.
453 * @method onAvailable
455 onAvailable: function () {
459 * Returns a reference to the linked element
461 * @return {HTMLElement} the html element
465 this._domRef = Dom.get(this.id);
472 * Returns a reference to the actual element to drag. By default this is
473 * the same as the html element, but it can be assigned to another
474 * element. An example of this can be found in YAHOO.util.DDProxy
476 * @return {HTMLElement} the html element
478 getDragEl: function() {
479 return Dom.get(this.dragElId);
483 * Sets up the DragDrop object. Must be called in the constructor of any
484 * YAHOO.util.DragDrop subclass
486 * @param id the id of the linked element
487 * @param {String} sGroup the group of related items
488 * @param {object} config configuration attributes
490 init: function(id, sGroup, config) {
491 this.initTarget(id, sGroup, config);
492 Event.on(this.id, "mousedown", this.handleMouseDown, this, true);
493 // Event.on(this.id, "selectstart", Event.preventDefault);
497 * Initializes Targeting functionality only... the object does not
498 * get a mousedown handler.
500 * @param id the id of the linked element
501 * @param {String} sGroup the group of related items
502 * @param {object} config configuration attributes
504 initTarget: function(id, sGroup, config) {
506 // configuration attributes
507 this.config = config || {};
509 // create a local reference to the drag and drop manager
510 this.DDM = YAHOO.util.DDM;
511 // initialize the groups array
514 // assume that we have an element reference instead of an id if the
515 // parameter is not a string
516 if (typeof id !== "string") {
517 YAHOO.log("id is not a string, assuming it is an HTMLElement");
518 id = Dom.generateId(id);
524 // add to an interaction group
525 this.addToGroup((sGroup) ? sGroup : "default");
527 // We don't want to register this as the handle with the manager
528 // so we just set the id rather than calling the setter.
529 this.handleElId = id;
531 Event.onAvailable(id, this.handleOnAvailable, this, true);
534 // the linked element is the element that gets dragged by default
535 this.setDragElId(id);
537 // by default, clicked anchors will not start drag operations.
538 // @TODO what else should be here? Probably form fields.
539 this.invalidHandleTypes = { A: "A" };
540 this.invalidHandleIds = {};
541 this.invalidHandleClasses = [];
547 * Applies the configuration parameters that were passed into the constructor.
548 * This is supposed to happen at each level through the inheritance chain. So
549 * a DDProxy implentation will execute apply config on DDProxy, DD, and
550 * DragDrop in order to get all of the parameters that are available in
552 * @method applyConfig
554 applyConfig: function() {
556 // configurable properties:
557 // padding, isTarget, maintainOffset, primaryButtonOnly
558 this.padding = this.config.padding || [0, 0, 0, 0];
559 this.isTarget = (this.config.isTarget !== false);
560 this.maintainOffset = (this.config.maintainOffset);
561 this.primaryButtonOnly = (this.config.primaryButtonOnly !== false);
566 * Executed when the linked element is available
567 * @method handleOnAvailable
570 handleOnAvailable: function() {
571 this.available = true;
572 this.resetConstraints();
577 * Configures the padding for the target zone in px. Effectively expands
578 * (or reduces) the virtual object size for targeting calculations.
579 * Supports css-style shorthand; if only one parameter is passed, all sides
580 * will have that padding, and if only two are passed, the top and bottom
581 * will have the first param, the left and right the second.
583 * @param {int} iTop Top pad
584 * @param {int} iRight Right pad
585 * @param {int} iBot Bot pad
586 * @param {int} iLeft Left pad
588 setPadding: function(iTop, iRight, iBot, iLeft) {
589 // this.padding = [iLeft, iRight, iTop, iBot];
590 if (!iRight && 0 !== iRight) {
591 this.padding = [iTop, iTop, iTop, iTop];
592 } else if (!iBot && 0 !== iBot) {
593 this.padding = [iTop, iRight, iTop, iRight];
595 this.padding = [iTop, iRight, iBot, iLeft];
600 * Stores the initial placement of the linked element.
601 * @method setInitialPosition
602 * @param {int} diffX the X offset, default 0
603 * @param {int} diffY the Y offset, default 0
605 setInitPosition: function(diffX, diffY) {
606 var el = this.getEl();
608 if (!this.DDM.verifyEl(el)) {
615 var p = Dom.getXY( el );
617 this.initPageX = p[0] - dx;
618 this.initPageY = p[1] - dy;
620 this.lastPageX = p[0];
621 this.lastPageY = p[1];
624 this.setStartPosition(p);
628 * Sets the start position of the element. This is set when the obj
629 * is initialized, the reset when a drag is started.
630 * @method setStartPosition
631 * @param pos current position (from previous lookup)
634 setStartPosition: function(pos) {
635 var p = pos || Dom.getXY( this.getEl() );
637 this.deltaSetXY = null;
639 this.startPageX = p[0];
640 this.startPageY = p[1];
644 * Add this instance to a group of related drag/drop objects. All
645 * instances belong to at least one group, and can belong to as many
648 * @param sGroup {string} the name of the group
650 addToGroup: function(sGroup) {
651 this.groups[sGroup] = true;
652 this.DDM.regDragDrop(this, sGroup);
656 * Remove's this instance from the supplied interaction group
657 * @method removeFromGroup
658 * @param {string} sGroup The group to drop
660 removeFromGroup: function(sGroup) {
661 if (this.groups[sGroup]) {
662 delete this.groups[sGroup];
665 this.DDM.removeDDFromGroup(this, sGroup);
669 * Allows you to specify that an element other than the linked element
670 * will be moved with the cursor during a drag
671 * @method setDragElId
672 * @param id {string} the id of the element that will be used to initiate the drag
674 setDragElId: function(id) {
679 * Allows you to specify a child of the linked element that should be
680 * used to initiate the drag operation. An example of this would be if
681 * you have a content div with text and links. Clicking anywhere in the
682 * content area would normally start the drag operation. Use this method
683 * to specify that an element inside of the content div is the element
684 * that starts the drag operation.
685 * @method setHandleElId
686 * @param id {string} the id of the element that will be used to
689 setHandleElId: function(id) {
690 if (typeof id !== "string") {
691 YAHOO.log("id is not a string, assuming it is an HTMLElement");
692 id = Dom.generateId(id);
694 this.handleElId = id;
695 this.DDM.regHandle(this.id, id);
699 * Allows you to set an element outside of the linked element as a drag
701 * @method setOuterHandleElId
702 * @param id the id of the element that will be used to initiate the drag
704 setOuterHandleElId: function(id) {
705 if (typeof id !== "string") {
706 YAHOO.log("id is not a string, assuming it is an HTMLElement");
707 id = Dom.generateId(id);
709 Event.on(id, "mousedown",
710 this.handleMouseDown, this, true);
711 this.setHandleElId(id);
713 this.hasOuterHandles = true;
717 * Remove all drag and drop hooks for this element
721 Event.removeListener(this.id, "mousedown",
722 this.handleMouseDown);
724 this.DDM._remove(this);
728 * Returns true if this instance is locked, or the drag drop mgr is locked
729 * (meaning that all drag/drop is disabled on the page.)
731 * @return {boolean} true if this obj or all drag/drop is locked, else
734 isLocked: function() {
735 return (this.DDM.isLocked() || this.locked);
739 * Fired when this object is clicked
740 * @method handleMouseDown
742 * @param {YAHOO.util.DragDrop} oDD the clicked dd object (this dd obj)
745 handleMouseDown: function(e, oDD) {
747 var button = e.which || e.button;
749 if (this.primaryButtonOnly && button > 1) {
753 if (this.isLocked()) {
757 this.DDM.refreshCache(this.groups);
759 // setTimeout( function() { self.DDM.refreshCache(self.groups); }, 0);
761 // Only process the event if we really clicked within the linked
762 // element. The reason we make this check is that in the case that
763 // another element was moved between the clicked element and the
764 // cursor in the time between the mousedown and mouseup events. When
765 // this happens, the element gets the next mousedown event
766 // regardless of where on the screen it happened.
767 var pt = new YAHOO.util.Point(Event.getPageX(e), Event.getPageY(e));
768 if (!this.hasOuterHandles && !this.DDM.isOverTarget(pt, this) ) {
770 if (this.clickValidator(e)) {
773 // set the initial element position
774 this.setStartPosition();
779 this.DDM.handleMouseDown(e, this);
781 this.DDM.stopEvent(e);
789 clickValidator: function(e) {
790 var target = Event.getTarget(e);
791 return ( this.isValidHandleChild(target) &&
792 (this.id == this.handleElId ||
793 this.DDM.handleWasClicked(target, this.id)) );
797 * Allows you to specify a tag name that should not start a drag operation
798 * when clicked. This is designed to facilitate embedding links within a
799 * drag handle that do something other than start the drag.
800 * @method addInvalidHandleType
801 * @param {string} tagName the type of element to exclude
803 addInvalidHandleType: function(tagName) {
804 var type = tagName.toUpperCase();
805 this.invalidHandleTypes[type] = type;
809 * Lets you to specify an element id for a child of a drag handle
810 * that should not initiate a drag
811 * @method addInvalidHandleId
812 * @param {string} id the element id of the element you wish to ignore
814 addInvalidHandleId: function(id) {
815 if (typeof id !== "string") {
816 YAHOO.log("id is not a string, assuming it is an HTMLElement");
817 id = Dom.generateId(id);
819 this.invalidHandleIds[id] = id;
823 * Lets you specify a css class of elements that will not initiate a drag
824 * @method addInvalidHandleClass
825 * @param {string} cssClass the class of the elements you wish to ignore
827 addInvalidHandleClass: function(cssClass) {
828 this.invalidHandleClasses.push(cssClass);
832 * Unsets an excluded tag name set by addInvalidHandleType
833 * @method removeInvalidHandleType
834 * @param {string} tagName the type of element to unexclude
836 removeInvalidHandleType: function(tagName) {
837 var type = tagName.toUpperCase();
838 // this.invalidHandleTypes[type] = null;
839 delete this.invalidHandleTypes[type];
843 * Unsets an invalid handle id
844 * @method removeInvalidHandleId
845 * @param {string} id the id of the element to re-enable
847 removeInvalidHandleId: function(id) {
848 if (typeof id !== "string") {
849 YAHOO.log("id is not a string, assuming it is an HTMLElement");
850 id = Dom.generateId(id);
852 delete this.invalidHandleIds[id];
856 * Unsets an invalid css class
857 * @method removeInvalidHandleClass
858 * @param {string} cssClass the class of the element(s) you wish to
861 removeInvalidHandleClass: function(cssClass) {
862 for (var i=0, len=this.invalidHandleClasses.length; i<len; ++i) {
863 if (this.invalidHandleClasses[i] == cssClass) {
864 delete this.invalidHandleClasses[i];
870 * Checks the tag exclusion list to see if this click should be ignored
871 * @method isValidHandleChild
872 * @param {HTMLElement} node the HTMLElement to evaluate
873 * @return {boolean} true if this is a valid tag type, false if not
875 isValidHandleChild: function(node) {
878 // var n = (node.nodeName == "#text") ? node.parentNode : node;
881 nodeName = node.nodeName.toUpperCase();
883 nodeName = node.nodeName;
885 valid = valid && !this.invalidHandleTypes[nodeName];
886 valid = valid && !this.invalidHandleIds[node.id];
888 for (var i=0, len=this.invalidHandleClasses.length; valid && i<len; ++i) {
889 valid = !Dom.hasClass(node, this.invalidHandleClasses[i]);
898 * Create the array of horizontal tick marks if an interval was specified
899 * in setXConstraint().
903 setXTicks: function(iStartX, iTickSize) {
905 this.xTickSize = iTickSize;
909 for (var i = this.initPageX; i >= this.minX; i = i - iTickSize) {
911 this.xTicks[this.xTicks.length] = i;
916 for (i = this.initPageX; i <= this.maxX; i = i + iTickSize) {
918 this.xTicks[this.xTicks.length] = i;
923 this.xTicks.sort(this.DDM.numericSort) ;
927 * Create the array of vertical tick marks if an interval was specified in
932 setYTicks: function(iStartY, iTickSize) {
934 this.yTickSize = iTickSize;
938 for (var i = this.initPageY; i >= this.minY; i = i - iTickSize) {
940 this.yTicks[this.yTicks.length] = i;
945 for (i = this.initPageY; i <= this.maxY; i = i + iTickSize) {
947 this.yTicks[this.yTicks.length] = i;
952 this.yTicks.sort(this.DDM.numericSort) ;
956 * By default, the element can be dragged any place on the screen. Use
957 * this method to limit the horizontal travel of the element. Pass in
958 * 0,0 for the parameters if you want to lock the drag to the y axis.
959 * @method setXConstraint
960 * @param {int} iLeft the number of pixels the element can move to the left
961 * @param {int} iRight the number of pixels the element can move to the
963 * @param {int} iTickSize optional parameter for specifying that the
965 * should move iTickSize pixels at a time.
967 setXConstraint: function(iLeft, iRight, iTickSize) {
968 this.leftConstraint = iLeft;
969 this.rightConstraint = iRight;
971 this.minX = this.initPageX - iLeft;
972 this.maxX = this.initPageX + iRight;
973 if (iTickSize) { this.setXTicks(this.initPageX, iTickSize); }
975 this.constrainX = true;
979 * Clears any constraints applied to this instance. Also clears ticks
980 * since they can't exist independent of a constraint at this time.
981 * @method clearConstraints
983 clearConstraints: function() {
984 this.constrainX = false;
985 this.constrainY = false;
990 * Clears any tick interval defined for this instance
993 clearTicks: function() {
1001 * By default, the element can be dragged any place on the screen. Set
1002 * this to limit the vertical travel of the element. Pass in 0,0 for the
1003 * parameters if you want to lock the drag to the x axis.
1004 * @method setYConstraint
1005 * @param {int} iUp the number of pixels the element can move up
1006 * @param {int} iDown the number of pixels the element can move down
1007 * @param {int} iTickSize optional parameter for specifying that the
1008 * element should move iTickSize pixels at a time.
1010 setYConstraint: function(iUp, iDown, iTickSize) {
1011 this.topConstraint = iUp;
1012 this.bottomConstraint = iDown;
1014 this.minY = this.initPageY - iUp;
1015 this.maxY = this.initPageY + iDown;
1016 if (iTickSize) { this.setYTicks(this.initPageY, iTickSize); }
1018 this.constrainY = true;
1023 * resetConstraints must be called if you manually reposition a dd element.
1024 * @method resetConstraints
1025 * @param {boolean} maintainOffset
1027 resetConstraints: function() {
1030 // Maintain offsets if necessary
1031 if (this.initPageX || this.initPageX === 0) {
1032 // figure out how much this thing has moved
1033 var dx = (this.maintainOffset) ? this.lastPageX - this.initPageX : 0;
1034 var dy = (this.maintainOffset) ? this.lastPageY - this.initPageY : 0;
1036 this.setInitPosition(dx, dy);
1038 // This is the first time we have detected the element's position
1040 this.setInitPosition();
1043 if (this.constrainX) {
1044 this.setXConstraint( this.leftConstraint,
1045 this.rightConstraint,
1049 if (this.constrainY) {
1050 this.setYConstraint( this.topConstraint,
1051 this.bottomConstraint,
1057 * Normally the drag element is moved pixel by pixel, but we can specify
1058 * that it move a number of pixels at a time. This method resolves the
1059 * location when we have it set up like this.
1061 * @param {int} val where we want to place the object
1062 * @param {int[]} tickArray sorted array of valid points
1063 * @return {int} the closest tick
1066 getTick: function(val, tickArray) {
1069 // If tick interval is not defined, it is effectively 1 pixel,
1070 // so we return the value passed to us.
1072 } else if (tickArray[0] >= val) {
1073 // The value is lower than the first tick, so we return the first
1075 return tickArray[0];
1077 for (var i=0, len=tickArray.length; i<len; ++i) {
1079 if (tickArray[next] && tickArray[next] >= val) {
1080 var diff1 = val - tickArray[i];
1081 var diff2 = tickArray[next] - val;
1082 return (diff2 > diff1) ? tickArray[i] : tickArray[next];
1086 // The value is larger than the last tick, so we return the last
1088 return tickArray[tickArray.length - 1];
1095 * @return {string} string representation of the dd obj
1097 toString: function() {
1098 return ("DragDrop " + this.id);
1105 * The drag and drop utility provides a framework for building drag and drop
1106 * applications. In addition to enabling drag and drop for specific elements,
1107 * the drag and drop elements are tracked by the manager class, and the
1108 * interactions between the various elements are tracked during the drag and
1109 * the implementing code is notified about these important moments.
1111 * @title Drag and Drop
1112 * @requires yahoo,dom,event
1113 * @namespace YAHOO.util
1116 // Only load the library once. Rewriting the manager class would orphan
1117 // existing drag and drop instances.
1118 if (!YAHOO.util.DragDropMgr) {
1121 * DragDropMgr is a singleton that tracks the element interaction for
1122 * all DragDrop items in the window. Generally, you will not call
1123 * this class directly, but it does have helper methods that could
1124 * be useful in your DragDrop implementations.
1125 * @class DragDropMgr
1128 YAHOO.util.DragDropMgr = function() {
1130 var Event = YAHOO.util.Event;
1135 * Two dimensional Array of registered DragDrop objects. The first
1136 * dimension is the DragDrop item group, the second the DragDrop
1139 * @type {string: string}
1146 * Array of element ids defined as drag handles. Used to determine
1147 * if the element that generated the mousedown event is actually the
1148 * handle and not the html element itself.
1149 * @property handleIds
1150 * @type {string: string}
1157 * the DragDrop object that is currently being dragged
1158 * @property dragCurrent
1166 * the DragDrop object(s) that are being hovered over
1167 * @property dragOvers
1175 * the X distance between the cursor and the object being dragged
1184 * the Y distance between the cursor and the object being dragged
1193 * Flag to determine if we should prevent the default behavior of the
1194 * events we define. By default this is true, but this can be set to
1195 * false if you need the default behavior (not recommended)
1196 * @property preventDefault
1200 preventDefault: true,
1203 * Flag to determine if we should stop the propagation of the events
1204 * we generate. This is true by default but you may want to set it to
1205 * false if the html element contains other features that require the
1207 * @property stopPropagation
1211 stopPropagation: true,
1214 * Internal flag that is set to true when drag and drop has been
1216 * @property initialized
1223 * All drag and drop can be disabled.
1231 * Called the first time an element is registered.
1237 this.initialized = true;
1241 * In point mode, drag and drop interaction is defined by the
1242 * location of the cursor during the drag/drop
1251 * In intersect mode, drag and drop interaction is defined by the
1252 * cursor position or the amount of overlap of two or more drag and
1254 * @property INTERSECT
1262 * In intersect mode, drag and drop interaction is defined only by the
1263 * overlap of two or more drag and drop objects.
1264 * @property STRICT_INTERSECT
1269 STRICT_INTERSECT: 2,
1272 * The current drag and drop mode. Default: POINT
1280 * Runs method on all drag and drop objects
1281 * @method _execOnAll
1285 _execOnAll: function(sMethod, args) {
1286 for (var i in this.ids) {
1287 for (var j in this.ids[i]) {
1288 var oDD = this.ids[i][j];
1289 if (! this.isTypeOfDD(oDD)) {
1292 oDD[sMethod].apply(oDD, args);
1298 * Drag and drop initialization. Sets up the global event handlers
1303 _onLoad: function() {
1308 Event.on(document, "mouseup", this.handleMouseUp, this, true);
1309 Event.on(document, "mousemove", this.handleMouseMove, this, true);
1310 Event.on(window, "unload", this._onUnload, this, true);
1311 Event.on(window, "resize", this._onResize, this, true);
1312 // Event.on(window, "mouseout", this._test);
1317 * Reset constraints on all drag and drop objs
1322 _onResize: function(e) {
1323 this._execOnAll("resetConstraints", []);
1327 * Lock all drag and drop functionality
1331 lock: function() { this.locked = true; },
1334 * Unlock all drag and drop functionality
1338 unlock: function() { this.locked = false; },
1341 * Is drag and drop locked?
1343 * @return {boolean} True if drag and drop is locked, false otherwise.
1346 isLocked: function() { return this.locked; },
1349 * Location cache that is set for all drag drop objects when a drag is
1350 * initiated, cleared when the drag is finished.
1351 * @property locationCache
1358 * Set useCache to false if you want to force object the lookup of each
1359 * drag and drop linked element constantly during a drag.
1360 * @property useCache
1367 * The number of pixels that the mouse needs to move after the
1368 * mousedown before the drag is initiated. Default=3;
1369 * @property clickPixelThresh
1373 clickPixelThresh: 3,
1376 * The number of milliseconds after the mousedown event to initiate the
1377 * drag if we don't get a mouseup event. Default=1000
1378 * @property clickTimeThresh
1382 clickTimeThresh: 1000,
1385 * Flag that indicates that either the drag pixel threshold or the
1386 * mousdown time threshold has been met
1387 * @property dragThreshMet
1392 dragThreshMet: false,
1395 * Timeout used for the click time threshold
1396 * @property clickTimeout
1404 * The X position of the mousedown event stored for later use when a
1405 * drag threshold is met.
1414 * The Y position of the mousedown event stored for later use when a
1415 * drag threshold is met.
1424 * Each DragDrop instance must be registered with the DragDropMgr.
1425 * This is executed in DragDrop.init()
1426 * @method regDragDrop
1427 * @param {DragDrop} oDD the DragDrop object to register
1428 * @param {String} sGroup the name of the group this element belongs to
1431 regDragDrop: function(oDD, sGroup) {
1432 if (!this.initialized) { this.init(); }
1434 if (!this.ids[sGroup]) {
1435 this.ids[sGroup] = {};
1437 this.ids[sGroup][oDD.id] = oDD;
1441 * Removes the supplied dd instance from the supplied group. Executed
1442 * by DragDrop.removeFromGroup, so don't call this function directly.
1443 * @method removeDDFromGroup
1447 removeDDFromGroup: function(oDD, sGroup) {
1448 if (!this.ids[sGroup]) {
1449 this.ids[sGroup] = {};
1452 var obj = this.ids[sGroup];
1453 if (obj && obj[oDD.id]) {
1459 * Unregisters a drag and drop item. This is executed in
1460 * DragDrop.unreg, use that method instead of calling this directly.
1465 _remove: function(oDD) {
1466 for (var g in oDD.groups) {
1467 if (g && this.ids[g][oDD.id]) {
1468 delete this.ids[g][oDD.id];
1471 delete this.handleIds[oDD.id];
1475 * Each DragDrop handle element must be registered. This is done
1476 * automatically when executing DragDrop.setHandleElId()
1478 * @param {String} sDDId the DragDrop id this element is a handle for
1479 * @param {String} sHandleId the id of the element that is the drag
1483 regHandle: function(sDDId, sHandleId) {
1484 if (!this.handleIds[sDDId]) {
1485 this.handleIds[sDDId] = {};
1487 this.handleIds[sDDId][sHandleId] = sHandleId;
1491 * Utility function to determine if a given element has been
1492 * registered as a drag drop item.
1493 * @method isDragDrop
1494 * @param {String} id the element id to check
1495 * @return {boolean} true if this element is a DragDrop item,
1499 isDragDrop: function(id) {
1500 return ( this.getDDById(id) ) ? true : false;
1504 * Returns the drag and drop instances that are in all groups the
1505 * passed in instance belongs to.
1506 * @method getRelated
1507 * @param {DragDrop} p_oDD the obj to get related data for
1508 * @param {boolean} bTargetsOnly if true, only return targetable objs
1509 * @return {DragDrop[]} the related instances
1512 getRelated: function(p_oDD, bTargetsOnly) {
1514 for (var i in p_oDD.groups) {
1515 for (j in this.ids[i]) {
1516 var dd = this.ids[i][j];
1517 if (! this.isTypeOfDD(dd)) {
1520 if (!bTargetsOnly || dd.isTarget) {
1521 oDDs[oDDs.length] = dd;
1530 * Returns true if the specified dd target is a legal target for
1531 * the specifice drag obj
1532 * @method isLegalTarget
1533 * @param {DragDrop} the drag obj
1534 * @param {DragDrop} the target
1535 * @return {boolean} true if the target is a legal target for the
1539 isLegalTarget: function (oDD, oTargetDD) {
1540 var targets = this.getRelated(oDD, true);
1541 for (var i=0, len=targets.length;i<len;++i) {
1542 if (targets[i].id == oTargetDD.id) {
1551 * My goal is to be able to transparently determine if an object is
1552 * typeof DragDrop, and the exact subclass of DragDrop. typeof
1553 * returns "object", oDD.constructor.toString() always returns
1554 * "DragDrop" and not the name of the subclass. So for now it just
1555 * evaluates a well-known variable in DragDrop.
1556 * @method isTypeOfDD
1557 * @param {Object} the object to evaluate
1558 * @return {boolean} true if typeof oDD = DragDrop
1561 isTypeOfDD: function (oDD) {
1562 return (oDD && oDD.__ygDragDrop);
1566 * Utility function to determine if a given element has been
1567 * registered as a drag drop handle for the given Drag Drop object.
1569 * @param {String} id the element id to check
1570 * @return {boolean} true if this element is a DragDrop handle, false
1574 isHandle: function(sDDId, sHandleId) {
1575 return ( this.handleIds[sDDId] &&
1576 this.handleIds[sDDId][sHandleId] );
1580 * Returns the DragDrop instance for a given id
1582 * @param {String} id the id of the DragDrop object
1583 * @return {DragDrop} the drag drop object, null if it is not found
1586 getDDById: function(id) {
1587 for (var i in this.ids) {
1588 if (this.ids[i][id]) {
1589 return this.ids[i][id];
1596 * Fired after a registered DragDrop object gets the mousedown event.
1597 * Sets up the events required to track the object being dragged
1598 * @method handleMouseDown
1599 * @param {Event} e the event
1600 * @param oDD the DragDrop object being dragged
1604 handleMouseDown: function(e, oDD) {
1606 this.currentTarget = YAHOO.util.Event.getTarget(e);
1608 this.dragCurrent = oDD;
1610 var el = oDD.getEl();
1612 // track start position
1613 this.startX = YAHOO.util.Event.getPageX(e);
1614 this.startY = YAHOO.util.Event.getPageY(e);
1616 this.deltaX = this.startX - el.offsetLeft;
1617 this.deltaY = this.startY - el.offsetTop;
1619 this.dragThreshMet = false;
1621 this.clickTimeout = setTimeout(
1623 var DDM = YAHOO.util.DDM;
1624 DDM.startDrag(DDM.startX, DDM.startY);
1626 this.clickTimeThresh );
1630 * Fired when either the drag pixel threshol or the mousedown hold
1631 * time threshold has been met.
1633 * @param x {int} the X position of the original mousedown
1634 * @param y {int} the Y position of the original mousedown
1637 startDrag: function(x, y) {
1638 clearTimeout(this.clickTimeout);
1639 if (this.dragCurrent) {
1640 this.dragCurrent.b4StartDrag(x, y);
1641 this.dragCurrent.startDrag(x, y);
1643 this.dragThreshMet = true;
1647 * Internal function to handle the mouseup event. Will be invoked
1648 * from the context of the document.
1649 * @method handleMouseUp
1650 * @param {Event} e the event
1654 handleMouseUp: function(e) {
1656 if (! this.dragCurrent) {
1660 clearTimeout(this.clickTimeout);
1662 if (this.dragThreshMet) {
1663 this.fireEvents(e, true);
1673 * Utility to stop event propagation and event default, if these
1674 * features are turned on.
1676 * @param {Event} e the event as returned by this.getEvent()
1679 stopEvent: function(e) {
1680 if (this.stopPropagation) {
1681 YAHOO.util.Event.stopPropagation(e);
1684 if (this.preventDefault) {
1685 YAHOO.util.Event.preventDefault(e);
1690 * Internal function to clean up event handlers after the drag
1691 * operation is complete
1693 * @param {Event} e the event
1697 stopDrag: function(e) {
1699 // Fire the drag end event for the item that was dragged
1700 if (this.dragCurrent) {
1701 if (this.dragThreshMet) {
1702 this.dragCurrent.b4EndDrag(e);
1703 this.dragCurrent.endDrag(e);
1706 this.dragCurrent.onMouseUp(e);
1709 this.dragCurrent = null;
1710 this.dragOvers = {};
1714 * Internal function to handle the mousemove event. Will be invoked
1715 * from the context of the html element.
1717 * @TODO figure out what we can do about mouse events lost when the
1718 * user drags objects beyond the window boundary. Currently we can
1719 * detect this in internet explorer by verifying that the mouse is
1720 * down during the mousemove event. Firefox doesn't give us the
1721 * button state on the mousemove event.
1722 * @method handleMouseMove
1723 * @param {Event} e the event
1727 handleMouseMove: function(e) {
1728 if (! this.dragCurrent) {
1732 // var button = e.which || e.button;
1734 // check for IE mouseup outside of page boundary
1735 if (YAHOO.util.Event.isIE && !e.button) {
1737 return this.handleMouseUp(e);
1740 if (!this.dragThreshMet) {
1741 var diffX = Math.abs(this.startX - YAHOO.util.Event.getPageX(e));
1742 var diffY = Math.abs(this.startY - YAHOO.util.Event.getPageY(e));
1743 if (diffX > this.clickPixelThresh ||
1744 diffY > this.clickPixelThresh) {
1745 this.startDrag(this.startX, this.startY);
1749 if (this.dragThreshMet) {
1750 this.dragCurrent.b4Drag(e);
1751 this.dragCurrent.onDrag(e);
1752 this.fireEvents(e, false);
1761 * Iterates over all of the DragDrop elements to find ones we are
1762 * hovering over or dropping on
1763 * @method fireEvents
1764 * @param {Event} e the event
1765 * @param {boolean} isDrop is this a drop op or a mouseover op?
1769 fireEvents: function(e, isDrop) {
1770 var dc = this.dragCurrent;
1772 // If the user did the mouse up outside of the window, we could
1773 // get here even though we have ended the drag.
1774 if (!dc || dc.isLocked()) {
1778 var x = YAHOO.util.Event.getPageX(e);
1779 var y = YAHOO.util.Event.getPageY(e);
1780 var pt = new YAHOO.util.Point(x,y);
1782 // cache the previous dragOver array
1790 // Check to see if the object(s) we were hovering over is no longer
1791 // being hovered over so we can fire the onDragOut event
1792 for (var i in this.dragOvers) {
1794 var ddo = this.dragOvers[i];
1796 if (! this.isTypeOfDD(ddo)) {
1800 if (! this.isOverTarget(pt, ddo, this.mode)) {
1801 outEvts.push( ddo );
1805 delete this.dragOvers[i];
1808 for (var sGroup in dc.groups) {
1810 if ("string" != typeof sGroup) {
1814 for (i in this.ids[sGroup]) {
1815 var oDD = this.ids[sGroup][i];
1816 if (! this.isTypeOfDD(oDD)) {
1820 if (oDD.isTarget && !oDD.isLocked() && oDD != dc) {
1821 if (this.isOverTarget(pt, oDD, this.mode)) {
1822 // look for drop interactions
1824 dropEvts.push( oDD );
1825 // look for drag enter and drag over interactions
1828 // initial drag over: dragEnter fires
1829 if (!oldOvers[oDD.id]) {
1830 enterEvts.push( oDD );
1831 // subsequent drag overs: dragOver fires
1833 overEvts.push( oDD );
1836 this.dragOvers[oDD.id] = oDD;
1844 if (outEvts.length) {
1845 dc.b4DragOut(e, outEvts);
1846 dc.onDragOut(e, outEvts);
1849 if (enterEvts.length) {
1850 dc.onDragEnter(e, enterEvts);
1853 if (overEvts.length) {
1854 dc.b4DragOver(e, overEvts);
1855 dc.onDragOver(e, overEvts);
1858 if (dropEvts.length) {
1859 dc.b4DragDrop(e, dropEvts);
1860 dc.onDragDrop(e, dropEvts);
1864 // fire dragout events
1866 for (i=0, len=outEvts.length; i<len; ++i) {
1867 dc.b4DragOut(e, outEvts[i].id);
1868 dc.onDragOut(e, outEvts[i].id);
1871 // fire enter events
1872 for (i=0,len=enterEvts.length; i<len; ++i) {
1873 // dc.b4DragEnter(e, oDD.id);
1874 dc.onDragEnter(e, enterEvts[i].id);
1878 for (i=0,len=overEvts.length; i<len; ++i) {
1879 dc.b4DragOver(e, overEvts[i].id);
1880 dc.onDragOver(e, overEvts[i].id);
1884 for (i=0, len=dropEvts.length; i<len; ++i) {
1885 dc.b4DragDrop(e, dropEvts[i].id);
1886 dc.onDragDrop(e, dropEvts[i].id);
1891 // notify about a drop that did not find a target
1892 if (isDrop && !dropEvts.length) {
1893 dc.onInvalidDrop(e);
1899 * Helper function for getting the best match from the list of drag
1900 * and drop objects returned by the drag and drop events when we are
1901 * in INTERSECT mode. It returns either the first object that the
1902 * cursor is over, or the object that has the greatest overlap with
1903 * the dragged element.
1904 * @method getBestMatch
1905 * @param {DragDrop[]} dds The array of drag and drop objects
1907 * @return {DragDrop} The best single match
1910 getBestMatch: function(dds) {
1913 var len = dds.length;
1918 // Loop through the targeted items
1919 for (var i=0; i<len; ++i) {
1921 // If the cursor is over the object, it wins. If the
1922 // cursor is over multiple matches, the first one we come
1924 if (this.mode == this.INTERSECT && dd.cursorIsOver) {
1927 // Otherwise the object with the most overlap wins
1929 if (!winner || !winner.overlap || (dd.overlap &&
1930 winner.overlap.getArea() < dd.overlap.getArea())) {
1941 * Refreshes the cache of the top-left and bottom-right points of the
1942 * drag and drop objects in the specified group(s). This is in the
1943 * format that is stored in the drag and drop instance, so typical
1946 * YAHOO.util.DragDropMgr.refreshCache(ddinstance.groups);
1950 * YAHOO.util.DragDropMgr.refreshCache({group1:true, group2:true});
1952 * @TODO this really should be an indexed array. Alternatively this
1953 * method could accept both.
1954 * @method refreshCache
1955 * @param {Object} groups an associative array of groups to refresh
1958 refreshCache: function(groups) {
1959 for (var sGroup in groups) {
1960 if ("string" != typeof sGroup) {
1963 for (var i in this.ids[sGroup]) {
1964 var oDD = this.ids[sGroup][i];
1966 if (this.isTypeOfDD(oDD)) {
1967 // if (this.isTypeOfDD(oDD) && oDD.isTarget) {
1968 var loc = this.getLocation(oDD);
1970 this.locationCache[oDD.id] = loc;
1972 delete this.locationCache[oDD.id];
1973 // this will unregister the drag and drop object if
1974 // the element is not in a usable state
1983 * This checks to make sure an element exists and is in the DOM. The
1984 * main purpose is to handle cases where innerHTML is used to remove
1985 * drag and drop objects from the DOM. IE provides an 'unspecified
1986 * error' when trying to access the offsetParent of such an element
1988 * @param {HTMLElement} el the element to check
1989 * @return {boolean} true if the element looks usable
1992 verifyEl: function(el) {
1995 var parent = el.offsetParent;
2007 * Returns a Region object containing the drag and drop element's position
2008 * and size, including the padding configured for it
2009 * @method getLocation
2010 * @param {DragDrop} oDD the drag and drop object to get the
2012 * @return {YAHOO.util.Region} a Region object representing the total area
2013 * the element occupies, including any padding
2014 * the instance is configured for.
2017 getLocation: function(oDD) {
2018 if (! this.isTypeOfDD(oDD)) {
2022 var el = oDD.getEl(), pos, x1, x2, y1, y2, t, r, b, l;
2025 pos= YAHOO.util.Dom.getXY(el);
2033 x2 = x1 + el.offsetWidth;
2035 y2 = y1 + el.offsetHeight;
2037 t = y1 - oDD.padding[0];
2038 r = x2 + oDD.padding[1];
2039 b = y2 + oDD.padding[2];
2040 l = x1 - oDD.padding[3];
2042 return new YAHOO.util.Region( t, r, b, l );
2046 * Checks the cursor location to see if it over the target
2047 * @method isOverTarget
2048 * @param {YAHOO.util.Point} pt The point to evaluate
2049 * @param {DragDrop} oTarget the DragDrop object we are inspecting
2050 * @return {boolean} true if the mouse is over the target
2054 isOverTarget: function(pt, oTarget, intersect) {
2055 // use cache if available
2056 var loc = this.locationCache[oTarget.id];
2057 if (!loc || !this.useCache) {
2058 loc = this.getLocation(oTarget);
2059 this.locationCache[oTarget.id] = loc;
2067 oTarget.cursorIsOver = loc.contains( pt );
2069 // DragDrop is using this as a sanity check for the initial mousedown
2070 // in this case we are done. In POINT mode, if the drag obj has no
2071 // contraints, we are also done. Otherwise we need to evaluate the
2072 // location of the target as related to the actual location of the
2074 var dc = this.dragCurrent;
2075 if (!dc || !dc.getTargetCoord ||
2076 (!intersect && !dc.constrainX && !dc.constrainY)) {
2077 return oTarget.cursorIsOver;
2080 oTarget.overlap = null;
2082 // Get the current location of the drag element, this is the
2083 // location of the mouse event less the delta that represents
2084 // where the original mousedown happened on the element. We
2085 // need to consider constraints and ticks as well.
2086 var pos = dc.getTargetCoord(pt.x, pt.y);
2088 var el = dc.getDragEl();
2089 var curRegion = new YAHOO.util.Region( pos.y,
2090 pos.x + el.offsetWidth,
2091 pos.y + el.offsetHeight,
2094 var overlap = curRegion.intersect(loc);
2097 oTarget.overlap = overlap;
2098 return (intersect) ? true : oTarget.cursorIsOver;
2105 * unload event handler
2110 _onUnload: function(e, me) {
2115 * Cleans up the drag and drop events and objects.
2120 unregAll: function() {
2122 if (this.dragCurrent) {
2124 this.dragCurrent = null;
2127 this._execOnAll("unreg", []);
2129 for (i in this.elementCache) {
2130 delete this.elementCache[i];
2133 this.elementCache = {};
2138 * A cache of DOM elements
2139 * @property elementCache
2146 * Get the wrapper for the DOM element specified
2147 * @method getElWrapper
2148 * @param {String} id the id of the element to get
2149 * @return {YAHOO.util.DDM.ElementWrapper} the wrapped element
2151 * @deprecated This wrapper isn't that useful
2154 getElWrapper: function(id) {
2155 var oWrapper = this.elementCache[id];
2156 if (!oWrapper || !oWrapper.el) {
2157 oWrapper = this.elementCache[id] =
2158 new this.ElementWrapper(YAHOO.util.Dom.get(id));
2164 * Returns the actual DOM element
2165 * @method getElement
2166 * @param {String} id the id of the elment to get
2167 * @return {Object} The element
2168 * @deprecated use YAHOO.util.Dom.get instead
2171 getElement: function(id) {
2172 return YAHOO.util.Dom.get(id);
2176 * Returns the style property for the DOM element (i.e.,
2177 * document.getElById(id).style)
2179 * @param {String} id the id of the elment to get
2180 * @return {Object} The style property of the element
2181 * @deprecated use YAHOO.util.Dom instead
2184 getCss: function(id) {
2185 var el = YAHOO.util.Dom.get(id);
2186 return (el) ? el.style : null;
2190 * Inner class for cached elements
2191 * @class DragDropMgr.ElementWrapper
2196 ElementWrapper: function(el) {
2201 this.el = el || null;
2206 this.id = this.el && el.id;
2208 * A reference to the style property
2211 this.css = this.el && el.style;
2215 * Returns the X position of an html element
2217 * @param el the element for which to get the position
2218 * @return {int} the X coordinate
2220 * @deprecated use YAHOO.util.Dom.getX instead
2223 getPosX: function(el) {
2224 return YAHOO.util.Dom.getX(el);
2228 * Returns the Y position of an html element
2230 * @param el the element for which to get the position
2231 * @return {int} the Y coordinate
2232 * @deprecated use YAHOO.util.Dom.getY instead
2235 getPosY: function(el) {
2236 return YAHOO.util.Dom.getY(el);
2240 * Swap two nodes. In IE, we use the native method, for others we
2241 * emulate the IE behavior
2243 * @param n1 the first node to swap
2244 * @param n2 the other node to swap
2247 swapNode: function(n1, n2) {
2251 var p = n2.parentNode;
2252 var s = n2.nextSibling;
2255 p.insertBefore(n1, n2);
2256 } else if (n2 == n1.nextSibling) {
2257 p.insertBefore(n2, n1);
2259 n1.parentNode.replaceChild(n2, n1);
2260 p.insertBefore(n1, s);
2266 * Returns the current scroll position
2271 getScroll: function () {
2272 var t, l, dde=document.documentElement, db=document.body;
2273 if (dde && (dde.scrollTop || dde.scrollLeft)) {
2280 YAHOO.log("could not get scroll property");
2282 return { top: t, left: l };
2286 * Returns the specified element style property
2288 * @param {HTMLElement} el the element
2289 * @param {string} styleProp the style property
2290 * @return {string} The value of the style property
2291 * @deprecated use YAHOO.util.Dom.getStyle
2294 getStyle: function(el, styleProp) {
2295 return YAHOO.util.Dom.getStyle(el, styleProp);
2299 * Gets the scrollTop
2300 * @method getScrollTop
2301 * @return {int} the document's scrollTop
2304 getScrollTop: function () { return this.getScroll().top; },
2307 * Gets the scrollLeft
2308 * @method getScrollLeft
2309 * @return {int} the document's scrollTop
2312 getScrollLeft: function () { return this.getScroll().left; },
2315 * Sets the x/y position of an element to the location of the
2318 * @param {HTMLElement} moveEl The element to move
2319 * @param {HTMLElement} targetEl The position reference element
2322 moveToEl: function (moveEl, targetEl) {
2323 var aCoord = YAHOO.util.Dom.getXY(targetEl);
2324 YAHOO.util.Dom.setXY(moveEl, aCoord);
2328 * Gets the client height
2329 * @method getClientHeight
2330 * @return {int} client height in px
2331 * @deprecated use YAHOO.util.Dom.getViewportHeight instead
2334 getClientHeight: function() {
2335 return YAHOO.util.Dom.getViewportHeight();
2339 * Gets the client width
2340 * @method getClientWidth
2341 * @return {int} client width in px
2342 * @deprecated use YAHOO.util.Dom.getViewportWidth instead
2345 getClientWidth: function() {
2346 return YAHOO.util.Dom.getViewportWidth();
2350 * Numeric array sort function
2351 * @method numericSort
2354 numericSort: function(a, b) { return (a - b); },
2358 * @property _timeoutCount
2365 * Trying to make the load order less important. Without this we get
2366 * an error if this file is loaded before the Event Utility.
2367 * @method _addListeners
2371 _addListeners: function() {
2372 var DDM = YAHOO.util.DDM;
2373 if ( YAHOO.util.Event && document ) {
2376 if (DDM._timeoutCount > 2000) {
2378 setTimeout(DDM._addListeners, 10);
2379 if (document && document.body) {
2380 DDM._timeoutCount += 1;
2387 * Recursively searches the immediate parent and all child nodes for
2388 * the handle element in order to determine wheter or not it was
2390 * @method handleWasClicked
2391 * @param node the html element to inspect
2394 handleWasClicked: function(node, id) {
2395 if (this.isHandle(id, node.id)) {
2398 // check to see if this is a text node child of the one we want
2399 var p = node.parentNode;
2402 if (this.isHandle(id, p.id)) {
2417 // shorter alias, save a few bytes
2418 YAHOO.util.DDM = YAHOO.util.DragDropMgr;
2419 YAHOO.util.DDM._addListeners();
2424 * A DragDrop implementation where the linked element follows the
2425 * mouse cursor during a drag.
2427 * @extends YAHOO.util.DragDrop
2429 * @param {String} id the id of the linked element
2430 * @param {String} sGroup the group of related DragDrop items
2431 * @param {object} config an object containing configurable attributes
2432 * Valid properties for DD:
2435 YAHOO.util.DD = function(id, sGroup, config) {
2437 this.init(id, sGroup, config);
2441 YAHOO.extend(YAHOO.util.DD, YAHOO.util.DragDrop, {
2444 * When set to true, the utility automatically tries to scroll the browser
2445 * window wehn a drag and drop element is dragged near the viewport boundary.
2453 * Sets the pointer offset to the distance between the linked element's top
2454 * left corner and the location the element was clicked
2455 * @method autoOffset
2456 * @param {int} iPageX the X coordinate of the click
2457 * @param {int} iPageY the Y coordinate of the click
2459 autoOffset: function(iPageX, iPageY) {
2460 var x = iPageX - this.startPageX;
2461 var y = iPageY - this.startPageY;
2462 this.setDelta(x, y);
2466 * Sets the pointer offset. You can call this directly to force the
2467 * offset to be in a particular location (e.g., pass in 0,0 to set it
2468 * to the center of the object, as done in YAHOO.widget.Slider)
2470 * @param {int} iDeltaX the distance from the left
2471 * @param {int} iDeltaY the distance from the top
2473 setDelta: function(iDeltaX, iDeltaY) {
2474 this.deltaX = iDeltaX;
2475 this.deltaY = iDeltaY;
2479 * Sets the drag element to the location of the mousedown or click event,
2480 * maintaining the cursor location relative to the location on the element
2481 * that was clicked. Override this if you want to place the element in a
2482 * location other than where the cursor is.
2483 * @method setDragElPos
2484 * @param {int} iPageX the X coordinate of the mousedown or drag event
2485 * @param {int} iPageY the Y coordinate of the mousedown or drag event
2487 setDragElPos: function(iPageX, iPageY) {
2488 // the first time we do this, we are going to check to make sure
2489 // the element has css positioning
2491 var el = this.getDragEl();
2492 this.alignElWithMouse(el, iPageX, iPageY);
2496 * Sets the element to the location of the mousedown or click event,
2497 * maintaining the cursor location relative to the location on the element
2498 * that was clicked. Override this if you want to place the element in a
2499 * location other than where the cursor is.
2500 * @method alignElWithMouse
2501 * @param {HTMLElement} el the element to move
2502 * @param {int} iPageX the X coordinate of the mousedown or drag event
2503 * @param {int} iPageY the Y coordinate of the mousedown or drag event
2505 alignElWithMouse: function(el, iPageX, iPageY) {
2506 var oCoord = this.getTargetCoord(iPageX, iPageY);
2508 if (!this.deltaSetXY) {
2509 var aCoord = [oCoord.x, oCoord.y];
2510 YAHOO.util.Dom.setXY(el, aCoord);
2511 var newLeft = parseInt( YAHOO.util.Dom.getStyle(el, "left"), 10 );
2512 var newTop = parseInt( YAHOO.util.Dom.getStyle(el, "top" ), 10 );
2514 this.deltaSetXY = [ newLeft - oCoord.x, newTop - oCoord.y ];
2516 YAHOO.util.Dom.setStyle(el, "left", (oCoord.x + this.deltaSetXY[0]) + "px");
2517 YAHOO.util.Dom.setStyle(el, "top", (oCoord.y + this.deltaSetXY[1]) + "px");
2520 this.cachePosition(oCoord.x, oCoord.y);
2521 this.autoScroll(oCoord.x, oCoord.y, el.offsetHeight, el.offsetWidth);
2525 * Saves the most recent position so that we can reset the constraints and
2526 * tick marks on-demand. We need to know this so that we can calculate the
2527 * number of pixels the element is offset from its original position.
2528 * @method cachePosition
2529 * @param iPageX the current x position (optional, this just makes it so we
2530 * don't have to look it up again)
2531 * @param iPageY the current y position (optional, this just makes it so we
2532 * don't have to look it up again)
2534 cachePosition: function(iPageX, iPageY) {
2536 this.lastPageX = iPageX;
2537 this.lastPageY = iPageY;
2539 var aCoord = YAHOO.util.Dom.getXY(this.getEl());
2540 this.lastPageX = aCoord[0];
2541 this.lastPageY = aCoord[1];
2546 * Auto-scroll the window if the dragged object has been moved beyond the
2547 * visible window boundary.
2548 * @method autoScroll
2549 * @param {int} x the drag element's x position
2550 * @param {int} y the drag element's y position
2551 * @param {int} h the height of the drag element
2552 * @param {int} w the width of the drag element
2555 autoScroll: function(x, y, h, w) {
2558 // The client height
2559 var clientH = this.DDM.getClientHeight();
2562 var clientW = this.DDM.getClientWidth();
2564 // The amt scrolled down
2565 var st = this.DDM.getScrollTop();
2567 // The amt scrolled right
2568 var sl = this.DDM.getScrollLeft();
2570 // Location of the bottom of the element
2573 // Location of the right of the element
2576 // The distance from the cursor to the bottom of the visible area,
2577 // adjusted so that we don't scroll if the cursor is beyond the
2578 // element drag constraints
2579 var toBot = (clientH + st - y - this.deltaY);
2581 // The distance from the cursor to the right of the visible area
2582 var toRight = (clientW + sl - x - this.deltaX);
2585 // How close to the edge the cursor must be before we scroll
2586 // var thresh = (document.all) ? 100 : 40;
2589 // How many pixels to scroll per autoscroll op. This helps to reduce
2590 // clunky scrolling. IE is more sensitive about this ... it needs this
2591 // value to be higher.
2592 var scrAmt = (document.all) ? 80 : 30;
2594 // Scroll down if we are near the bottom of the visible page and the
2595 // obj extends below the crease
2596 if ( bot > clientH && toBot < thresh ) {
2597 window.scrollTo(sl, st + scrAmt);
2600 // Scroll up if the window is scrolled down and the top of the object
2601 // goes above the top border
2602 if ( y < st && st > 0 && y - st < thresh ) {
2603 window.scrollTo(sl, st - scrAmt);
2606 // Scroll right if the obj is beyond the right border and the cursor is
2608 if ( right > clientW && toRight < thresh ) {
2609 window.scrollTo(sl + scrAmt, st);
2612 // Scroll left if the window has been scrolled to the right and the obj
2613 // extends past the left border
2614 if ( x < sl && sl > 0 && x - sl < thresh ) {
2615 window.scrollTo(sl - scrAmt, st);
2621 * Finds the location the element should be placed if we want to move
2622 * it to where the mouse location less the click offset would place us.
2623 * @method getTargetCoord
2624 * @param {int} iPageX the X coordinate of the click
2625 * @param {int} iPageY the Y coordinate of the click
2626 * @return an object that contains the coordinates (Object.x and Object.y)
2629 getTargetCoord: function(iPageX, iPageY) {
2632 var x = iPageX - this.deltaX;
2633 var y = iPageY - this.deltaY;
2635 if (this.constrainX) {
2636 if (x < this.minX) { x = this.minX; }
2637 if (x > this.maxX) { x = this.maxX; }
2640 if (this.constrainY) {
2641 if (y < this.minY) { y = this.minY; }
2642 if (y > this.maxY) { y = this.maxY; }
2645 x = this.getTick(x, this.xTicks);
2646 y = this.getTick(y, this.yTicks);
2653 * Sets up config options specific to this class. Overrides
2654 * YAHOO.util.DragDrop, but all versions of this method through the
2655 * inheritance chain are called
2657 applyConfig: function() {
2658 YAHOO.util.DD.superclass.applyConfig.call(this);
2659 this.scroll = (this.config.scroll !== false);
2663 * Event that fires prior to the onMouseDown event. Overrides
2664 * YAHOO.util.DragDrop.
2666 b4MouseDown: function(e) {
2667 // this.resetConstraints();
2668 this.autoOffset(YAHOO.util.Event.getPageX(e),
2669 YAHOO.util.Event.getPageY(e));
2673 * Event that fires prior to the onDrag event. Overrides
2674 * YAHOO.util.DragDrop.
2676 b4Drag: function(e) {
2677 this.setDragElPos(YAHOO.util.Event.getPageX(e),
2678 YAHOO.util.Event.getPageY(e));
2681 toString: function() {
2682 return ("DD " + this.id);
2685 //////////////////////////////////////////////////////////////////////////
2686 // Debugging ygDragDrop events that can be overridden
2687 //////////////////////////////////////////////////////////////////////////
2689 startDrag: function(x, y) {
2692 onDrag: function(e) {
2695 onDragEnter: function(e, id) {
2698 onDragOver: function(e, id) {
2701 onDragOut: function(e, id) {
2704 onDragDrop: function(e, id) {
2707 endDrag: function(e) {
2714 * A DragDrop implementation that inserts an empty, bordered div into
2715 * the document that follows the cursor during drag operations. At the time of
2716 * the click, the frame div is resized to the dimensions of the linked html
2717 * element, and moved to the exact location of the linked element.
2719 * References to the "frame" element refer to the single proxy element that
2720 * was created to be dragged in place of all DDProxy elements on the
2724 * @extends YAHOO.util.DD
2726 * @param {String} id the id of the linked html element
2727 * @param {String} sGroup the group of related DragDrop objects
2728 * @param {object} config an object containing configurable attributes
2729 * Valid properties for DDProxy in addition to those in DragDrop:
2730 * resizeFrame, centerFrame, dragElId
2732 YAHOO.util.DDProxy = function(id, sGroup, config) {
2734 this.init(id, sGroup, config);
2740 * The default drag frame div id
2741 * @property YAHOO.util.DDProxy.dragElId
2745 YAHOO.util.DDProxy.dragElId = "ygddfdiv";
2747 YAHOO.extend(YAHOO.util.DDProxy, YAHOO.util.DD, {
2750 * By default we resize the drag frame to be the same size as the element
2751 * we want to drag (this is to get the frame effect). We can turn it off
2752 * if we want a different behavior.
2753 * @property resizeFrame
2759 * By default the frame is positioned exactly where the drag element is, so
2760 * we use the cursor offset provided by YAHOO.util.DD. Another option that works only if
2761 * you do not have constraints on the obj is to have the drag frame centered
2762 * around the cursor. Set centerFrame to true for this effect.
2763 * @property centerFrame
2769 * Creates the proxy element if it does not yet exist
2770 * @method createFrame
2772 createFrame: function() {
2774 var body = document.body;
2776 if (!body || !body.firstChild) {
2777 setTimeout( function() { self.createFrame(); }, 50 );
2781 var div = this.getDragEl();
2784 div = document.createElement("div");
2785 div.id = this.dragElId;
2788 s.position = "absolute";
2789 s.visibility = "hidden";
2791 s.border = "2px solid #aaa";
2794 // appendChild can blow up IE if invoked prior to the window load event
2795 // while rendering a table. It is possible there are other scenarios
2796 // that would cause this to happen as well.
2797 body.insertBefore(div, body.firstChild);
2802 * Initialization for the drag frame element. Must be called in the
2803 * constructor of all subclasses
2806 initFrame: function() {
2810 applyConfig: function() {
2811 YAHOO.util.DDProxy.superclass.applyConfig.call(this);
2813 this.resizeFrame = (this.config.resizeFrame !== false);
2814 this.centerFrame = (this.config.centerFrame);
2815 this.setDragElId(this.config.dragElId || YAHOO.util.DDProxy.dragElId);
2819 * Resizes the drag frame to the dimensions of the clicked object, positions
2820 * it over the object, and finally displays it
2822 * @param {int} iPageX X click position
2823 * @param {int} iPageY Y click position
2826 showFrame: function(iPageX, iPageY) {
2827 var el = this.getEl();
2828 var dragEl = this.getDragEl();
2829 var s = dragEl.style;
2831 this._resizeProxy();
2833 if (this.centerFrame) {
2834 this.setDelta( Math.round(parseInt(s.width, 10)/2),
2835 Math.round(parseInt(s.height, 10)/2) );
2838 this.setDragElPos(iPageX, iPageY);
2840 YAHOO.util.Dom.setStyle(dragEl, "visibility", "visible");
2844 * The proxy is automatically resized to the dimensions of the linked
2845 * element when a drag is initiated, unless resizeFrame is set to false
2846 * @method _resizeProxy
2849 _resizeProxy: function() {
2850 if (this.resizeFrame) {
2851 var DOM = YAHOO.util.Dom;
2852 var el = this.getEl();
2853 var dragEl = this.getDragEl();
2855 var bt = parseInt( DOM.getStyle(dragEl, "borderTopWidth" ), 10);
2856 var br = parseInt( DOM.getStyle(dragEl, "borderRightWidth" ), 10);
2857 var bb = parseInt( DOM.getStyle(dragEl, "borderBottomWidth" ), 10);
2858 var bl = parseInt( DOM.getStyle(dragEl, "borderLeftWidth" ), 10);
2860 if (isNaN(bt)) { bt = 0; }
2861 if (isNaN(br)) { br = 0; }
2862 if (isNaN(bb)) { bb = 0; }
2863 if (isNaN(bl)) { bl = 0; }
2866 var newWidth = Math.max(0, el.offsetWidth - br - bl);
2867 var newHeight = Math.max(0, el.offsetHeight - bt - bb);
2870 DOM.setStyle( dragEl, "width", newWidth + "px" );
2871 DOM.setStyle( dragEl, "height", newHeight + "px" );
2875 // overrides YAHOO.util.DragDrop
2876 b4MouseDown: function(e) {
2877 var x = YAHOO.util.Event.getPageX(e);
2878 var y = YAHOO.util.Event.getPageY(e);
2879 this.autoOffset(x, y);
2880 this.setDragElPos(x, y);
2883 // overrides YAHOO.util.DragDrop
2884 b4StartDrag: function(x, y) {
2885 // show the drag frame
2886 this.showFrame(x, y);
2889 // overrides YAHOO.util.DragDrop
2890 b4EndDrag: function(e) {
2891 YAHOO.util.Dom.setStyle(this.getDragEl(), "visibility", "hidden");
2894 // overrides YAHOO.util.DragDrop
2895 // By default we try to move the element to the last location of the frame.
2896 // This is so that the default behavior mirrors that of YAHOO.util.DD.
2897 endDrag: function(e) {
2898 var DOM = YAHOO.util.Dom;
2899 var lel = this.getEl();
2900 var del = this.getDragEl();
2902 // Show the drag frame briefly so we can get its position
2903 // del.style.visibility = "";
2904 DOM.setStyle(del, "visibility", "");
2906 // Hide the linked element before the move to get around a Safari
2908 //lel.style.visibility = "hidden";
2909 DOM.setStyle(lel, "visibility", "hidden");
2910 YAHOO.util.DDM.moveToEl(lel, del);
2911 //del.style.visibility = "hidden";
2912 DOM.setStyle(del, "visibility", "hidden");
2913 //lel.style.visibility = "";
2914 DOM.setStyle(lel, "visibility", "");
2917 toString: function() {
2918 return ("DDProxy " + this.id);
2923 * A DragDrop implementation that does not move, but can be a drop
2924 * target. You would get the same result by simply omitting implementation
2925 * for the event callbacks, but this way we reduce the processing cost of the
2926 * event listener and the callbacks.
2928 * @extends YAHOO.util.DragDrop
2930 * @param {String} id the id of the element that is a drop target
2931 * @param {String} sGroup the group of related DragDrop objects
2932 * @param {object} config an object containing configurable attributes
2933 * Valid properties for DDTarget in addition to those in
2937 YAHOO.util.DDTarget = function(id, sGroup, config) {
2939 this.initTarget(id, sGroup, config);
2943 // YAHOO.util.DDTarget.prototype = new YAHOO.util.DragDrop();
2944 YAHOO.extend(YAHOO.util.DDTarget, YAHOO.util.DragDrop, {
2945 toString: function() {
2946 return ("DDTarget " + this.id);