2 * jQuery UI Sortable 1.10.2
5 * Copyright 2013 jQuery Foundation and other contributors
6 * Released under the MIT license.
7 * http://jquery.org/license
9 * http://api.jqueryui.com/sortable/
16 (function( $, undefined ) {
18 /*jshint loopfunc: true */
20 function isOverAxis( x, reference, size ) {
21 return ( x > reference ) && ( x < ( reference + size ) );
24 function isFloating(item) {
25 return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
28 $.widget("ui.sortable", $.ui.mouse, {
30 widgetEventPrefix: "sort",
40 forcePlaceholderSize: false,
41 forceHelperSize: false,
50 scrollSensitivity: 20,
53 tolerance: "intersect",
73 this.containerCache = {};
74 this.element.addClass("ui-sortable");
79 //Let's determine if the items are being displayed horizontally
80 this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false;
82 //Let's determine the parent's offset
83 this.offset = this.element.offset();
85 //Initialize mouse events for interaction
93 _destroy: function() {
95 .removeClass("ui-sortable ui-sortable-disabled");
98 for ( var i = this.items.length - 1; i >= 0; i-- ) {
99 this.items[i].item.removeData(this.widgetName + "-item");
105 _setOption: function(key, value){
106 if ( key === "disabled" ) {
107 this.options[ key ] = value;
109 this.widget().toggleClass( "ui-sortable-disabled", !!value );
111 // Don't call widget base _setOption for disable as it adds ui-state-disabled class
112 $.Widget.prototype._setOption.apply(this, arguments);
116 _mouseCapture: function(event, overrideHandle) {
117 var currentItem = null,
121 if (this.reverting) {
125 if(this.options.disabled || this.options.type === "static") {
129 //We have to refresh the items data once first
130 this._refreshItems(event);
132 //Find out if the clicked node (or one of its parents) is a actual item in this.items
133 $(event.target).parents().each(function() {
134 if($.data(this, that.widgetName + "-item") === that) {
135 currentItem = $(this);
139 if($.data(event.target, that.widgetName + "-item") === that) {
140 currentItem = $(event.target);
146 if(this.options.handle && !overrideHandle) {
147 $(this.options.handle, currentItem).find("*").addBack().each(function() {
148 if(this === event.target) {
157 this.currentItem = currentItem;
158 this._removeCurrentsFromItems();
163 _mouseStart: function(event, overrideHandle, noActivation) {
168 this.currentContainer = this;
170 //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
171 this.refreshPositions();
173 //Create and append the visible helper
174 this.helper = this._createHelper(event);
176 //Cache the helper size
177 this._cacheHelperProportions();
180 * - Position generation -
181 * This block generates everything position related - it's the core of draggables.
184 //Cache the margins of the original element
185 this._cacheMargins();
187 //Get the next scrolling parent
188 this.scrollParent = this.helper.scrollParent();
190 //The element's absolute position on the page minus margins
191 this.offset = this.currentItem.offset();
193 top: this.offset.top - this.margins.top,
194 left: this.offset.left - this.margins.left
197 $.extend(this.offset, {
198 click: { //Where the click happened, relative to the element
199 left: event.pageX - this.offset.left,
200 top: event.pageY - this.offset.top
202 parent: this._getParentOffset(),
203 relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
206 // Only after we got the offset, we can change the helper's position to absolute
207 // TODO: Still need to figure out a way to make relative sorting possible
208 this.helper.css("position", "absolute");
209 this.cssPosition = this.helper.css("position");
211 //Generate the original position
212 this.originalPosition = this._generatePosition(event);
213 this.originalPageX = event.pageX;
214 this.originalPageY = event.pageY;
216 //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
217 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
219 //Cache the former DOM position
220 this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
222 //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
223 if(this.helper[0] !== this.currentItem[0]) {
224 this.currentItem.hide();
227 //Create the placeholder
228 this._createPlaceholder();
230 //Set a containment if given in the options
232 this._setContainment();
235 if( o.cursor && o.cursor !== "auto" ) { // cursor option
236 body = this.document.find( "body" );
239 this.storedCursor = body.css( "cursor" );
240 body.css( "cursor", o.cursor );
242 this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
245 if(o.opacity) { // opacity option
246 if (this.helper.css("opacity")) {
247 this._storedOpacity = this.helper.css("opacity");
249 this.helper.css("opacity", o.opacity);
252 if(o.zIndex) { // zIndex option
253 if (this.helper.css("zIndex")) {
254 this._storedZIndex = this.helper.css("zIndex");
256 this.helper.css("zIndex", o.zIndex);
260 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
261 this.overflowOffset = this.scrollParent.offset();
265 this._trigger("start", event, this._uiHash());
267 //Recache the helper size
268 if(!this._preserveHelperProportions) {
269 this._cacheHelperProportions();
273 //Post "activate" events to possible containers
274 if( !noActivation ) {
275 for ( i = this.containers.length - 1; i >= 0; i-- ) {
276 this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
280 //Prepare possible droppables
282 $.ui.ddmanager.current = this;
285 if ($.ui.ddmanager && !o.dropBehaviour) {
286 $.ui.ddmanager.prepareOffsets(this, event);
289 this.dragging = true;
291 this.helper.addClass("ui-sortable-helper");
292 this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
297 _mouseDrag: function(event) {
298 var i, item, itemElement, intersection,
302 //Compute the helpers position
303 this.position = this._generatePosition(event);
304 this.positionAbs = this._convertPositionTo("absolute");
306 if (!this.lastPositionAbs) {
307 this.lastPositionAbs = this.positionAbs;
311 if(this.options.scroll) {
312 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
314 if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
315 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
316 } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
317 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
320 if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
321 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
322 } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
323 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
328 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
329 scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
330 } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
331 scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
334 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
335 scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
336 } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
337 scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
342 if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
343 $.ui.ddmanager.prepareOffsets(this, event);
347 //Regenerate the absolute position used for position checks
348 this.positionAbs = this._convertPositionTo("absolute");
350 //Set the helper position
351 if(!this.options.axis || this.options.axis !== "y") {
352 this.helper[0].style.left = this.position.left+"px";
354 if(!this.options.axis || this.options.axis !== "x") {
355 this.helper[0].style.top = this.position.top+"px";
359 for (i = this.items.length - 1; i >= 0; i--) {
361 //Cache variables and intersection, continue if no intersection
362 item = this.items[i];
363 itemElement = item.item[0];
364 intersection = this._intersectsWithPointer(item);
369 // Only put the placeholder inside the current Container, skip all
370 // items form other containers. This works because when moving
371 // an item from one container to another the
372 // currentContainer is switched before the placeholder is moved.
374 // Without this moving items in "sub-sortables" can cause the placeholder to jitter
375 // beetween the outer and inner container.
376 if (item.instance !== this.currentContainer) {
380 // cannot intersect with itself
381 // no useless actions that have been done before
382 // no action if the item moved is the parent of the item checked
383 if (itemElement !== this.currentItem[0] &&
384 this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
385 !$.contains(this.placeholder[0], itemElement) &&
386 (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
389 this.direction = intersection === 1 ? "down" : "up";
391 if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
392 this._rearrange(event, item);
397 this._trigger("change", event, this._uiHash());
402 //Post events to containers
403 this._contactContainers(event);
405 //Interconnect with droppables
407 $.ui.ddmanager.drag(this, event);
411 this._trigger("sort", event, this._uiHash());
413 this.lastPositionAbs = this.positionAbs;
418 _mouseStop: function(event, noPropagation) {
424 //If we are using droppables, inform the manager about the drop
425 if ($.ui.ddmanager && !this.options.dropBehaviour) {
426 $.ui.ddmanager.drop(this, event);
429 if(this.options.revert) {
431 cur = this.placeholder.offset(),
432 axis = this.options.axis,
435 if ( !axis || axis === "x" ) {
436 animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
438 if ( !axis || axis === "y" ) {
439 animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
441 this.reverting = true;
442 $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
446 this._clear(event, noPropagation);
457 this._mouseUp({ target: null });
459 if(this.options.helper === "original") {
460 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
462 this.currentItem.show();
465 //Post deactivating events to containers
466 for (var i = this.containers.length - 1; i >= 0; i--){
467 this.containers[i]._trigger("deactivate", null, this._uiHash(this));
468 if(this.containers[i].containerCache.over) {
469 this.containers[i]._trigger("out", null, this._uiHash(this));
470 this.containers[i].containerCache.over = 0;
476 if (this.placeholder) {
477 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
478 if(this.placeholder[0].parentNode) {
479 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
481 if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
482 this.helper.remove();
492 if(this.domPosition.prev) {
493 $(this.domPosition.prev).after(this.currentItem);
495 $(this.domPosition.parent).prepend(this.currentItem);
503 serialize: function(o) {
505 var items = this._getItemsAsjQuery(o && o.connected),
509 $(items).each(function() {
510 var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
512 str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
516 if(!str.length && o.key) {
517 str.push(o.key + "=");
520 return str.join("&");
524 toArray: function(o) {
526 var items = this._getItemsAsjQuery(o && o.connected),
531 items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
536 /* Be careful with the following core functions */
537 _intersectsWith: function(item) {
539 var x1 = this.positionAbs.left,
540 x2 = x1 + this.helperProportions.width,
541 y1 = this.positionAbs.top,
542 y2 = y1 + this.helperProportions.height,
547 dyClick = this.offset.click.top,
548 dxClick = this.offset.click.left,
549 isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
551 if ( this.options.tolerance === "pointer" ||
552 this.options.forcePointerForContainers ||
553 (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
555 return isOverElement;
558 return (l < x1 + (this.helperProportions.width / 2) && // Right Half
559 x2 - (this.helperProportions.width / 2) < r && // Left Half
560 t < y1 + (this.helperProportions.height / 2) && // Bottom Half
561 y2 - (this.helperProportions.height / 2) < b ); // Top Half
566 _intersectsWithPointer: function(item) {
568 var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
569 isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
570 isOverElement = isOverElementHeight && isOverElementWidth,
571 verticalDirection = this._getDragVerticalDirection(),
572 horizontalDirection = this._getDragHorizontalDirection();
574 if (!isOverElement) {
578 return this.floating ?
579 ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
580 : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
584 _intersectsWithSides: function(item) {
586 var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
587 isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
588 verticalDirection = this._getDragVerticalDirection(),
589 horizontalDirection = this._getDragHorizontalDirection();
591 if (this.floating && horizontalDirection) {
592 return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
594 return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
599 _getDragVerticalDirection: function() {
600 var delta = this.positionAbs.top - this.lastPositionAbs.top;
601 return delta !== 0 && (delta > 0 ? "down" : "up");
604 _getDragHorizontalDirection: function() {
605 var delta = this.positionAbs.left - this.lastPositionAbs.left;
606 return delta !== 0 && (delta > 0 ? "right" : "left");
609 refresh: function(event) {
610 this._refreshItems(event);
611 this.refreshPositions();
615 _connectWith: function() {
616 var options = this.options;
617 return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
620 _getItemsAsjQuery: function(connected) {
625 connectWith = this._connectWith();
627 if(connectWith && connected) {
628 for (i = connectWith.length - 1; i >= 0; i--){
629 cur = $(connectWith[i]);
630 for ( j = cur.length - 1; j >= 0; j--){
631 inst = $.data(cur[j], this.widgetFullName);
632 if(inst && inst !== this && !inst.options.disabled) {
633 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]);
639 queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]);
641 for (i = queries.length - 1; i >= 0; i--){
642 queries[i][0].each(function() {
651 _removeCurrentsFromItems: function() {
653 var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
655 this.items = $.grep(this.items, function (item) {
656 for (var j=0; j < list.length; j++) {
657 if(list[j] === item.item[0]) {
666 _refreshItems: function(event) {
669 this.containers = [this];
671 var i, j, cur, inst, targetData, _queries, item, queriesLength,
673 queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
674 connectWith = this._connectWith();
676 if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
677 for (i = connectWith.length - 1; i >= 0; i--){
678 cur = $(connectWith[i]);
679 for (j = cur.length - 1; j >= 0; j--){
680 inst = $.data(cur[j], this.widgetFullName);
681 if(inst && inst !== this && !inst.options.disabled) {
682 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
683 this.containers.push(inst);
689 for (i = queries.length - 1; i >= 0; i--) {
690 targetData = queries[i][1];
691 _queries = queries[i][0];
693 for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
694 item = $(_queries[j]);
696 item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
700 instance: targetData,
709 refreshPositions: function(fast) {
711 //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
712 if(this.offsetParent && this.helper) {
713 this.offset.parent = this._getParentOffset();
718 for (i = this.items.length - 1; i >= 0; i--){
719 item = this.items[i];
721 //We ignore calculating positions of all connected containers when we're not over them
722 if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
726 t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
729 item.width = t.outerWidth();
730 item.height = t.outerHeight();
738 if(this.options.custom && this.options.custom.refreshContainers) {
739 this.options.custom.refreshContainers.call(this);
741 for (i = this.containers.length - 1; i >= 0; i--){
742 p = this.containers[i].element.offset();
743 this.containers[i].containerCache.left = p.left;
744 this.containers[i].containerCache.top = p.top;
745 this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
746 this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
753 _createPlaceholder: function(that) {
758 if(!o.placeholder || o.placeholder.constructor === String) {
759 className = o.placeholder;
761 element: function() {
763 var nodeName = that.currentItem[0].nodeName.toLowerCase(),
764 element = $( that.document[0].createElement( nodeName ) )
765 .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
766 .removeClass("ui-sortable-helper");
768 if ( nodeName === "tr" ) {
769 // Use a high colspan to force the td to expand the full
770 // width of the table (browsers are smart enough to
771 // handle this properly)
772 element.append( "<td colspan='99'> </td>" );
773 } else if ( nodeName === "img" ) {
774 element.attr( "src", that.currentItem.attr( "src" ) );
778 element.css( "visibility", "hidden" );
783 update: function(container, p) {
785 // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
786 // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
787 if(className && !o.forcePlaceholderSize) {
791 //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
792 if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
793 if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
798 //Create the placeholder
799 that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
801 //Append it after the actual current item
802 that.currentItem.after(that.placeholder);
804 //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
805 o.placeholder.update(that, that.placeholder);
809 _contactContainers: function(event) {
810 var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating,
811 innermostContainer = null,
812 innermostIndex = null;
814 // get innermost container that intersects with item
815 for (i = this.containers.length - 1; i >= 0; i--) {
817 // never consider a container that's located within the item itself
818 if($.contains(this.currentItem[0], this.containers[i].element[0])) {
822 if(this._intersectsWith(this.containers[i].containerCache)) {
824 // if we've already found a container and it's more "inner" than this, then continue
825 if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
829 innermostContainer = this.containers[i];
833 // container doesn't intersect. trigger "out" event if necessary
834 if(this.containers[i].containerCache.over) {
835 this.containers[i]._trigger("out", event, this._uiHash(this));
836 this.containers[i].containerCache.over = 0;
842 // if no intersecting containers found, return
843 if(!innermostContainer) {
847 // move the item into the container if it's not there already
848 if(this.containers.length === 1) {
849 if (!this.containers[innermostIndex].containerCache.over) {
850 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
851 this.containers[innermostIndex].containerCache.over = 1;
855 //When entering a new container, we will find the item with the least distance and append our item near it
857 itemWithLeastDistance = null;
858 floating = innermostContainer.floating || isFloating(this.currentItem);
859 posProperty = floating ? "left" : "top";
860 sizeProperty = floating ? "width" : "height";
861 base = this.positionAbs[posProperty] + this.offset.click[posProperty];
862 for (j = this.items.length - 1; j >= 0; j--) {
863 if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
866 if(this.items[j].item[0] === this.currentItem[0]) {
869 if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) {
872 cur = this.items[j].item.offset()[posProperty];
874 if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
876 cur += this.items[j][sizeProperty];
879 if(Math.abs(cur - base) < dist) {
880 dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
881 this.direction = nearBottom ? "up": "down";
885 //Check if dropOnEmpty is enabled
886 if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
890 if(this.currentContainer === this.containers[innermostIndex]) {
894 itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
895 this._trigger("change", event, this._uiHash());
896 this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
897 this.currentContainer = this.containers[innermostIndex];
899 //Update the placeholder
900 this.options.placeholder.update(this.currentContainer, this.placeholder);
902 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
903 this.containers[innermostIndex].containerCache.over = 1;
909 _createHelper: function(event) {
911 var o = this.options,
912 helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
914 //Add the helper to the DOM if that didn't happen already
915 if(!helper.parents("body").length) {
916 $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
919 if(helper[0] === this.currentItem[0]) {
920 this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
923 if(!helper[0].style.width || o.forceHelperSize) {
924 helper.width(this.currentItem.width());
926 if(!helper[0].style.height || o.forceHelperSize) {
927 helper.height(this.currentItem.height());
934 _adjustOffsetFromHelper: function(obj) {
935 if (typeof obj === "string") {
936 obj = obj.split(" ");
938 if ($.isArray(obj)) {
939 obj = {left: +obj[0], top: +obj[1] || 0};
942 this.offset.click.left = obj.left + this.margins.left;
944 if ("right" in obj) {
945 this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
948 this.offset.click.top = obj.top + this.margins.top;
950 if ("bottom" in obj) {
951 this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
955 _getParentOffset: function() {
958 //Get the offsetParent and cache its position
959 this.offsetParent = this.helper.offsetParent();
960 var po = this.offsetParent.offset();
962 // This is a special case where we need to modify a offset calculated on start, since the following happened:
963 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
964 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
965 // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
966 if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
967 po.left += this.scrollParent.scrollLeft();
968 po.top += this.scrollParent.scrollTop();
971 // This needs to be actually done for all browsers, since pageX/pageY includes this information
972 // with an ugly IE fix
973 if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
974 po = { top: 0, left: 0 };
978 top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
979 left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
984 _getRelativeOffset: function() {
986 if(this.cssPosition === "relative") {
987 var p = this.currentItem.position();
989 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
990 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
993 return { top: 0, left: 0 };
998 _cacheMargins: function() {
1000 left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
1001 top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
1005 _cacheHelperProportions: function() {
1006 this.helperProportions = {
1007 width: this.helper.outerWidth(),
1008 height: this.helper.outerHeight()
1012 _setContainment: function() {
1016 if(o.containment === "parent") {
1017 o.containment = this.helper[0].parentNode;
1019 if(o.containment === "document" || o.containment === "window") {
1020 this.containment = [
1021 0 - this.offset.relative.left - this.offset.parent.left,
1022 0 - this.offset.relative.top - this.offset.parent.top,
1023 $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
1024 ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
1028 if(!(/^(document|window|parent)$/).test(o.containment)) {
1029 ce = $(o.containment)[0];
1030 co = $(o.containment).offset();
1031 over = ($(ce).css("overflow") !== "hidden");
1033 this.containment = [
1034 co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
1035 co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
1036 co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
1037 co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
1043 _convertPositionTo: function(d, pos) {
1046 pos = this.position;
1048 var mod = d === "absolute" ? 1 : -1,
1049 scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
1050 scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
1054 pos.top + // The absolute mouse position
1055 this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
1056 this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
1057 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
1060 pos.left + // The absolute mouse position
1061 this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
1062 this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
1063 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
1069 _generatePosition: function(event) {
1073 pageX = event.pageX,
1074 pageY = event.pageY,
1075 scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
1077 // This is another very weird special case that only happens for relative elements:
1078 // 1. If the css position is relative
1079 // 2. and the scroll parent is the document or similar to the offset parent
1080 // we have to refresh the relative offset during the scroll so there are no jumps
1081 if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
1082 this.offset.relative = this._getRelativeOffset();
1086 * - Position constraining -
1087 * Constrain the position to a mix of grid, containment.
1090 if(this.originalPosition) { //If we are not dragging yet, we won't check for options
1092 if(this.containment) {
1093 if(event.pageX - this.offset.click.left < this.containment[0]) {
1094 pageX = this.containment[0] + this.offset.click.left;
1096 if(event.pageY - this.offset.click.top < this.containment[1]) {
1097 pageY = this.containment[1] + this.offset.click.top;
1099 if(event.pageX - this.offset.click.left > this.containment[2]) {
1100 pageX = this.containment[2] + this.offset.click.left;
1102 if(event.pageY - this.offset.click.top > this.containment[3]) {
1103 pageY = this.containment[3] + this.offset.click.top;
1108 top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
1109 pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
1111 left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
1112 pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
1119 pageY - // The absolute mouse position
1120 this.offset.click.top - // Click offset (relative to the element)
1121 this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
1122 this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
1123 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
1126 pageX - // The absolute mouse position
1127 this.offset.click.left - // Click offset (relative to the element)
1128 this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
1129 this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
1130 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
1136 _rearrange: function(event, i, a, hardRefresh) {
1138 a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling));
1140 //Various things done here to improve the performance:
1141 // 1. we create a setTimeout, that calls refreshPositions
1142 // 2. on the instance, we have a counter variable, that get's higher after every append
1143 // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
1144 // 4. this lets only the last addition to the timeout stack through
1145 this.counter = this.counter ? ++this.counter : 1;
1146 var counter = this.counter;
1148 this._delay(function() {
1149 if(counter === this.counter) {
1150 this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
1156 _clear: function(event, noPropagation) {
1158 this.reverting = false;
1159 // We delay all events that have to be triggered to after the point where the placeholder has been removed and
1160 // everything else normalized again
1162 delayedTriggers = [];
1164 // We first have to update the dom position of the actual currentItem
1165 // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
1166 if(!this._noFinalSort && this.currentItem.parent().length) {
1167 this.placeholder.before(this.currentItem);
1169 this._noFinalSort = null;
1171 if(this.helper[0] === this.currentItem[0]) {
1172 for(i in this._storedCSS) {
1173 if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
1174 this._storedCSS[i] = "";
1177 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
1179 this.currentItem.show();
1182 if(this.fromOutside && !noPropagation) {
1183 delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
1185 if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
1186 delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
1189 // Check if the items Container has Changed and trigger appropriate
1191 if (this !== this.currentContainer) {
1192 if(!noPropagation) {
1193 delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
1194 delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
1195 delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
1200 //Post events to containers
1201 for (i = this.containers.length - 1; i >= 0; i--){
1202 if(!noPropagation) {
1203 delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
1205 if(this.containers[i].containerCache.over) {
1206 delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
1207 this.containers[i].containerCache.over = 0;
1211 //Do what was originally in plugins
1212 if ( this.storedCursor ) {
1213 this.document.find( "body" ).css( "cursor", this.storedCursor );
1214 this.storedStylesheet.remove();
1216 if(this._storedOpacity) {
1217 this.helper.css("opacity", this._storedOpacity);
1219 if(this._storedZIndex) {
1220 this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
1223 this.dragging = false;
1224 if(this.cancelHelperRemoval) {
1225 if(!noPropagation) {
1226 this._trigger("beforeStop", event, this._uiHash());
1227 for (i=0; i < delayedTriggers.length; i++) {
1228 delayedTriggers[i].call(this, event);
1229 } //Trigger all delayed events
1230 this._trigger("stop", event, this._uiHash());
1233 this.fromOutside = false;
1237 if(!noPropagation) {
1238 this._trigger("beforeStop", event, this._uiHash());
1241 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
1242 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
1244 if(this.helper[0] !== this.currentItem[0]) {
1245 this.helper.remove();
1249 if(!noPropagation) {
1250 for (i=0; i < delayedTriggers.length; i++) {
1251 delayedTriggers[i].call(this, event);
1252 } //Trigger all delayed events
1253 this._trigger("stop", event, this._uiHash());
1256 this.fromOutside = false;
1261 _trigger: function() {
1262 if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
1267 _uiHash: function(_inst) {
1268 var inst = _inst || this;
1270 helper: inst.helper,
1271 placeholder: inst.placeholder || $([]),
1272 position: inst.position,
1273 originalPosition: inst.originalPosition,
1274 offset: inst.positionAbs,
1275 item: inst.currentItem,
1276 sender: _inst ? _inst.element : null