jquery.dragsort.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // jQuery List DragSort v0.5.2
  2. // Website: http://dragsort.codeplex.com/
  3. // License: http://dragsort.codeplex.com/license
  4. (function($) {
  5. $.fn.dragsort = function(options) {
  6. if (options == "destroy") {
  7. $(this.selector).trigger("dragsort-uninit");
  8. return;
  9. }
  10. var opts = $.extend({}, $.fn.dragsort.defaults, options);
  11. var lists = [];
  12. var list = null, lastPos = null;
  13. this.each(function(i, cont) {
  14. //if list container is table, the browser automatically wraps rows in tbody if not specified so change list container to tbody so that children returns rows as user expected
  15. if ($(cont).is("table") && $(cont).children().size() == 1 && $(cont).children().is("tbody"))
  16. cont = $(cont).children().get(0);
  17. var newList = {
  18. draggedItem: null,
  19. placeHolderItem: null,
  20. pos: null,
  21. offset: null,
  22. offsetLimit: null,
  23. scroll: null,
  24. container: cont,
  25. init: function() {
  26. //set options to default values if not set
  27. opts.tagName = opts.tagName == "" ? ($(this.container).children().size() == 0 ? "li" : $(this.container).children().get(0).tagName.toLowerCase()) : opts.tagName;
  28. if (opts.itemSelector == "")
  29. opts.itemSelector = opts.tagName;
  30. if (opts.dragSelector == "")
  31. opts.dragSelector = opts.tagName;
  32. if (opts.placeHolderTemplate == "")
  33. opts.placeHolderTemplate = "<" + opts.tagName + ">&nbsp;</" + opts.tagName + ">";
  34. //listidx allows reference back to correct list variable instance
  35. $(this.container).attr("data-listidx", i).mousedown(this.grabItem).bind("dragsort-uninit", this.uninit);
  36. this.styleDragHandlers(true);
  37. },
  38. uninit: function() {
  39. var list = lists[$(this).attr("data-listidx")];
  40. $(list.container).unbind("mousedown", list.grabItem).unbind("dragsort-uninit");
  41. list.styleDragHandlers(false);
  42. },
  43. getItems: function() {
  44. return $(this.container).children(opts.itemSelector);
  45. },
  46. styleDragHandlers: function(cursor) {
  47. this.getItems().map(function() { return $(this).is(opts.dragSelector) ? this : $(this).find(opts.dragSelector).get(); }).css("cursor", cursor ? "pointer" : "");
  48. },
  49. grabItem: function(e) {
  50. var list = lists[$(this).attr("data-listidx")];
  51. var item = $(e.target).closest("[data-listidx] > " + opts.tagName).get(0);
  52. var insideMoveableItem = list.getItems().filter(function() { return this == item; }).size() > 0;
  53. //if not left click or if clicked on excluded element (e.g. text box) or not a moveable list item return
  54. if (e.which != 1 || $(e.target).is(opts.dragSelectorExclude) || $(e.target).closest(opts.dragSelectorExclude).size() > 0 || !insideMoveableItem)
  55. return;
  56. //prevents selection, stops issue on Fx where dragging hyperlink doesn't work and on IE where it triggers mousemove even though mouse hasn't moved,
  57. //does also stop being able to click text boxes hence dragging on text boxes by default is disabled in dragSelectorExclude
  58. //e.preventDefault();
  59. //change cursor to move while dragging
  60. var dragHandle = e.target;
  61. while (!$(dragHandle).is(opts.dragSelector)) {
  62. if (dragHandle == this) return;
  63. dragHandle = dragHandle.parentNode;
  64. }
  65. $(dragHandle).attr("data-cursor", $(dragHandle).css("cursor"));
  66. $(dragHandle).css("cursor", "move");
  67. //on mousedown wait for movement of mouse before triggering dragsort script (dragStart) to allow clicking of hyperlinks to work
  68. var listElem = this;
  69. var trigger = function() {
  70. list.dragStart.call(listElem, e);
  71. $(list.container).unbind("mousemove", trigger);
  72. };
  73. $(list.container).mousemove(trigger).mouseup(function() { $(list.container).unbind("mousemove", trigger); $(dragHandle).css("cursor", $(dragHandle).attr("data-cursor")); });
  74. },
  75. dragStart: function(e) {
  76. if (list != null && list.draggedItem != null)
  77. list.dropItem();
  78. list = lists[$(this).attr("data-listidx")];
  79. list.draggedItem = $(e.target).closest("[data-listidx] > " + opts.tagName)
  80. //record current position so on dragend we know if the dragged item changed position or not, not using getItems to allow dragsort to restore dragged item to original location in relation to fixed items
  81. list.draggedItem.attr("data-origpos", $(this).attr("data-listidx") + "-" + $(list.container).children().index(list.draggedItem));
  82. //calculate mouse offset relative to draggedItem
  83. var mt = parseInt(list.draggedItem.css("marginTop"));
  84. var ml = parseInt(list.draggedItem.css("marginLeft"));
  85. list.offset = list.draggedItem.offset();
  86. list.offset.top = e.pageY - list.offset.top + (isNaN(mt) ? 0 : mt) - 1;
  87. list.offset.left = e.pageX - list.offset.left + (isNaN(ml) ? 0 : ml) - 1;
  88. //calculate box the dragged item can't be dragged outside of
  89. if (!opts.dragBetween) {
  90. var containerHeight = $(list.container).outerHeight() == 0 ? Math.max(1, Math.round(0.5 + list.getItems().size() * list.draggedItem.outerWidth() / $(list.container).outerWidth())) * list.draggedItem.outerHeight() : $(list.container).outerHeight();
  91. list.offsetLimit = $(list.container).offset();
  92. list.offsetLimit.right = list.offsetLimit.left + $(list.container).outerWidth() - list.draggedItem.outerWidth();
  93. list.offsetLimit.bottom = list.offsetLimit.top + containerHeight - list.draggedItem.outerHeight();
  94. }
  95. //create placeholder item
  96. var h = list.draggedItem.height();
  97. var w = list.draggedItem.width();
  98. if (opts.tagName == "tr") {
  99. list.draggedItem.children().each(function() { $(this).width($(this).width()); });
  100. list.placeHolderItem = list.draggedItem.clone().attr("data-placeholder", true);
  101. list.draggedItem.after(list.placeHolderItem);
  102. //list.placeHolderItem.children().each(function() { $(this).css({ borderWidth:0, width: $(this).width() + 1, height: $(this).height() + 1 }).html("&nbsp;"); });
  103. list.placeHolderItem.children().each(function() { $(this).html("&nbsp;"); });
  104. } else {
  105. list.draggedItem.after(opts.placeHolderTemplate);
  106. list.placeHolderItem = list.draggedItem.next().css({ height: h, width: w }).attr("data-placeholder", true);
  107. }
  108. if (opts.tagName == "td") {
  109. var listTable = list.draggedItem.closest("table").get(0);
  110. $("<table id='" + listTable.id + "' style='border-width: 0px;' class='dragSortItem " + listTable.className + "'><tr></tr></table>").appendTo("body").children().append(list.draggedItem);
  111. }
  112. //style draggedItem while dragging
  113. var orig = list.draggedItem.attr("style");
  114. list.draggedItem.attr("data-origstyle", orig ? orig : "");
  115. list.draggedItem.css({ position: "absolute", opacity: 0.8, "z-index": 999, height: h, width: w });
  116. //auto-scroll setup
  117. list.scroll = { moveX: 0, moveY: 0, maxX: $(document).width() - $(window).width(), maxY: $(document).height() - $(window).height() };
  118. list.scroll.scrollY = window.setInterval(function() {
  119. if (opts.scrollContainer != window) {
  120. $(opts.scrollContainer).scrollTop($(opts.scrollContainer).scrollTop() + list.scroll.moveY);
  121. return;
  122. }
  123. var t = $(opts.scrollContainer).scrollTop();
  124. if (list.scroll.moveY > 0 && t < list.scroll.maxY || list.scroll.moveY < 0 && t > 0) {
  125. $(opts.scrollContainer).scrollTop(t + list.scroll.moveY);
  126. list.draggedItem.css("top", list.draggedItem.offset().top + list.scroll.moveY + 1);
  127. }
  128. }, 10);
  129. list.scroll.scrollX = window.setInterval(function() {
  130. if (opts.scrollContainer != window) {
  131. $(opts.scrollContainer).scrollLeft($(opts.scrollContainer).scrollLeft() + list.scroll.moveX);
  132. return;
  133. }
  134. var l = $(opts.scrollContainer).scrollLeft();
  135. if (list.scroll.moveX > 0 && l < list.scroll.maxX || list.scroll.moveX < 0 && l > 0) {
  136. $(opts.scrollContainer).scrollLeft(l + list.scroll.moveX);
  137. list.draggedItem.css("left", list.draggedItem.offset().left + list.scroll.moveX + 1);
  138. }
  139. }, 10);
  140. //misc
  141. $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); });
  142. list.setPos(e.pageX, e.pageY);
  143. $(document).bind("mousemove", list.swapItems);
  144. $(document).bind("mouseup", list.dropItem);
  145. if (opts.scrollContainer != window)
  146. $(window).bind("wheel", list.wheel);
  147. },
  148. //set position of draggedItem
  149. setPos: function(x, y) {
  150. //remove mouse offset so mouse cursor remains in same place on draggedItem instead of top left corner
  151. var top = y - this.offset.top;
  152. var left = x - this.offset.left;
  153. //limit top, left to within box draggedItem can't be dragged outside of
  154. if (!opts.dragBetween) {
  155. top = Math.min(this.offsetLimit.bottom, Math.max(top, this.offsetLimit.top));
  156. left = Math.min(this.offsetLimit.right, Math.max(left, this.offsetLimit.left));
  157. }
  158. //adjust top & left calculations to parent offset
  159. var parent = this.draggedItem.offsetParent().not("body").offset(); //offsetParent returns body even when it's static, if not static offset is only factoring margin
  160. if (parent != null) {
  161. top -= parent.top;
  162. left -= parent.left;
  163. }
  164. //set x or y auto-scroll amount
  165. if (opts.scrollContainer == window) {
  166. y -= $(window).scrollTop();
  167. x -= $(window).scrollLeft();
  168. y = Math.max(0, y - $(window).height() + 5) + Math.min(0, y - 5);
  169. x = Math.max(0, x - $(window).width() + 5) + Math.min(0, x - 5);
  170. } else {
  171. var cont = $(opts.scrollContainer);
  172. var offset = cont.offset();
  173. y = Math.max(0, y - cont.height() - offset.top) + Math.min(0, y - offset.top);
  174. x = Math.max(0, x - cont.width() - offset.left) + Math.min(0, x - offset.left);
  175. }
  176. list.scroll.moveX = x == 0 ? 0 : x * opts.scrollSpeed / Math.abs(x);
  177. list.scroll.moveY = y == 0 ? 0 : y * opts.scrollSpeed / Math.abs(y);
  178. //move draggedItem to new mouse cursor location
  179. this.draggedItem.css({ top: top, left: left });
  180. },
  181. //if scroll container is a div allow mouse wheel to scroll div instead of window when mouse is hovering over
  182. wheel: function(e) {
  183. if (list && opts.scrollContainer != window) {
  184. var cont = $(opts.scrollContainer);
  185. var offset = cont.offset();
  186. e = e.originalEvent;
  187. if (e.clientX > offset.left && e.clientX < offset.left + cont.width() && e.clientY > offset.top && e.clientY < offset.top + cont.height()) {
  188. var deltaY = (e.deltaMode == 0 ? 1 : 10) * e.deltaY;
  189. cont.scrollTop(cont.scrollTop() + deltaY);
  190. e.preventDefault();
  191. }
  192. }
  193. },
  194. //build a table recording all the positions of the moveable list items
  195. buildPositionTable: function() {
  196. var pos = [];
  197. this.getItems().not([list.draggedItem[0], list.placeHolderItem[0]]).each(function(i) {
  198. var loc = $(this).offset();
  199. loc.right = loc.left + $(this).outerWidth();
  200. loc.bottom = loc.top + $(this).outerHeight();
  201. loc.elm = this;
  202. pos[i] = loc;
  203. });
  204. this.pos = pos;
  205. },
  206. dropItem: function() {
  207. if (list.draggedItem == null)
  208. return;
  209. //list.draggedItem.attr("style", "") doesn't work on IE8 and jQuery 1.5 or lower
  210. //list.draggedItem.removeAttr("style") doesn't work on chrome and jQuery 1.6 (works jQuery 1.5 or lower)
  211. var orig = list.draggedItem.attr("data-origstyle");
  212. list.draggedItem.attr("style", orig);
  213. if (orig == "")
  214. list.draggedItem.removeAttr("style");
  215. list.draggedItem.removeAttr("data-origstyle");
  216. list.styleDragHandlers(true);
  217. list.placeHolderItem.before(list.draggedItem);
  218. list.placeHolderItem.remove();
  219. $("[data-droptarget], .dragSortItem").remove();
  220. window.clearInterval(list.scroll.scrollY);
  221. window.clearInterval(list.scroll.scrollX);
  222. //if position changed call dragEnd
  223. if (list.draggedItem.attr("data-origpos") != $(lists).index(list) + "-" + $(list.container).children().index(list.draggedItem))
  224. if (opts.dragEnd.apply(list.draggedItem) == false) { //if dragEnd returns false revert order
  225. var pos = list.draggedItem.attr("data-origpos").split('-');
  226. var nextItem = $(lists[pos[0]].container).children().not(list.draggedItem).eq(pos[1]);
  227. if (nextItem.size() > 0)
  228. nextItem.before(list.draggedItem);
  229. else if (pos[1] == 0) //was the only item in list
  230. $(lists[pos[0]].container).prepend(list.draggedItem);
  231. else //was the last item in list
  232. $(lists[pos[0]].container).append(list.draggedItem);
  233. }
  234. list.draggedItem.removeAttr("data-origpos");
  235. list.draggedItem = null;
  236. $(document).unbind("mousemove", list.swapItems);
  237. $(document).unbind("mouseup", list.dropItem);
  238. if (opts.scrollContainer != window)
  239. $(window).unbind("wheel", list.wheel);
  240. return false;
  241. },
  242. //swap the draggedItem (represented visually by placeholder) with the list item the it has been dragged on top of
  243. swapItems: function(e) {
  244. if (list.draggedItem == null)
  245. return false;
  246. //move draggedItem to mouse location
  247. list.setPos(e.pageX, e.pageY);
  248. //retrieve list and item position mouse cursor is over
  249. var ei = list.findPos(e.pageX, e.pageY);
  250. var nlist = list;
  251. for (var i = 0; ei == -1 && opts.dragBetween && i < lists.length; i++) {
  252. ei = lists[i].findPos(e.pageX, e.pageY);
  253. nlist = lists[i];
  254. }
  255. //if not over another moveable list item return
  256. if (ei == -1)
  257. return false;
  258. //save fixed items locations
  259. var children = function() { return $(nlist.container).children().not(nlist.draggedItem); };
  260. var fixed = children().not(opts.itemSelector).each(function(i) { this.idx = children().index(this); });
  261. //if moving draggedItem up or left place placeHolder before list item the dragged item is hovering over otherwise place it after
  262. if (lastPos == null || lastPos.top > list.draggedItem.offset().top || lastPos.left > list.draggedItem.offset().left)
  263. $(nlist.pos[ei].elm).before(list.placeHolderItem);
  264. else
  265. $(nlist.pos[ei].elm).after(list.placeHolderItem);
  266. //restore fixed items location
  267. fixed.each(function() {
  268. var elm = children().eq(this.idx).get(0);
  269. if (this != elm && children().index(this) < this.idx)
  270. $(this).insertAfter(elm);
  271. else if (this != elm)
  272. $(this).insertBefore(elm);
  273. });
  274. //misc
  275. $(lists).each(function(i, l) { l.createDropTargets(); l.buildPositionTable(); });
  276. lastPos = list.draggedItem.offset();
  277. return false;
  278. },
  279. //returns the index of the list item the mouse is over
  280. findPos: function(x, y) {
  281. for (var i = 0; i < this.pos.length; i++) {
  282. if (this.pos[i].left < x && this.pos[i].right > x && this.pos[i].top < y && this.pos[i].bottom > y)
  283. return i;
  284. }
  285. return -1;
  286. },
  287. //create drop targets which are placeholders at the end of other lists to allow dragging straight to the last position
  288. createDropTargets: function() {
  289. if (!opts.dragBetween)
  290. return;
  291. $(lists).each(function() {
  292. var ph = $(this.container).find("[data-placeholder]");
  293. var dt = $(this.container).find("[data-droptarget]");
  294. if (ph.size() > 0 && dt.size() > 0)
  295. dt.remove();
  296. else if (ph.size() == 0 && dt.size() == 0) {
  297. if (opts.tagName == "td")
  298. $(opts.placeHolderTemplate).attr("data-droptarget", true).appendTo(this.container);
  299. else
  300. //list.placeHolderItem.clone().removeAttr("data-placeholder") crashes in IE7 and jquery 1.5.1 (doesn't in jquery 1.4.2 or IE8)
  301. $(this.container).append(list.placeHolderItem.removeAttr("data-placeholder").clone().attr("data-droptarget", true));
  302. list.placeHolderItem.attr("data-placeholder", true);
  303. }
  304. });
  305. }
  306. };
  307. newList.init();
  308. lists.push(newList);
  309. });
  310. return this;
  311. };
  312. $.fn.dragsort.defaults = {
  313. tagName:"",
  314. itemSelector: "",
  315. dragSelector: "",
  316. dragSelectorExclude: "input, textarea",
  317. dragEnd: function() { },
  318. dragBetween: false,
  319. placeHolderTemplate: "",
  320. scrollContainer: window,
  321. scrollSpeed: 5
  322. };
  323. })(jQuery);