jquery.tablednd.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /**
  2. * TableDnD plug-in for JQuery, allows you to drag and drop table rows
  3. * You can set up various options to control how the system will work
  4. * Copyright (c) Denis Howlett <denish@isocra.com>
  5. * Licensed like jQuery, see http://docs.jquery.com/License.
  6. *
  7. * Configuration options:
  8. *
  9. * onDragStyle
  10. * This is the style that is assigned to the row during drag. There are limitations to the styles that can be
  11. * associated with a row (such as you can't assign a border--well you can, but it won't be
  12. * displayed). (So instead consider using onDragClass.) The CSS style to apply is specified as
  13. * a map (as used in the jQuery css(...) function).
  14. * onDropStyle
  15. * This is the style that is assigned to the row when it is dropped. As for onDragStyle, there are limitations
  16. * to what you can do. Also this replaces the original style, so again consider using onDragClass which
  17. * is simply added and then removed on drop.
  18. * onDragClass
  19. * This class is added for the duration of the drag and then removed when the row is dropped. It is more
  20. * flexible than using onDragStyle since it can be inherited by the row cells and other content. The default
  21. * is class is tDnD_whileDrag. So to use the default, simply customise this CSS class in your
  22. * stylesheet.
  23. * onDrop
  24. * Pass a function that will be called when the row is dropped. The function takes 2 parameters: the table
  25. * and the row that was dropped. You can work out the new order of the rows by using
  26. * table.rows.
  27. * onDragStart
  28. * Pass a function that will be called when the user starts dragging. The function takes 2 parameters: the
  29. * table and the row which the user has started to drag.
  30. * onAllowDrop
  31. * Pass a function that will be called as a row is over another row. If the function returns true, allow
  32. * dropping on that row, otherwise not. The function takes 2 parameters: the dragged row and the row under
  33. * the cursor. It returns a boolean: true allows the drop, false doesn't allow it.
  34. * scrollAmount
  35. * This is the number of pixels to scroll if the user moves the mouse cursor to the top or bottom of the
  36. * window. The page should automatically scroll up or down as appropriate (tested in IE6, IE7, Safari, FF2,
  37. * FF3 beta
  38. * dragHandle
  39. * This is the name of a class that you assign to one or more cells in each row that is draggable. If you
  40. * specify this class, then you are responsible for setting cursor: move in the CSS and only these cells
  41. * will have the drag behaviour. If you do not specify a dragHandle, then you get the old behaviour where
  42. * the whole row is draggable.
  43. *
  44. * Other ways to control behaviour:
  45. *
  46. * Add class="nodrop" to any rows for which you don't want to allow dropping, and class="nodrag" to any rows
  47. * that you don't want to be draggable.
  48. *
  49. * Inside the onDrop method you can also call $.tableDnD.serialize() this returns a string of the form
  50. * <tableID>[]=<rowID1>&<tableID>[]=<rowID2> so that you can send this back to the server. The table must have
  51. * an ID as must all the rows.
  52. *
  53. * Other methods:
  54. *
  55. * $("...").tableDnDUpdate()
  56. * Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
  57. * This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
  58. * The table maintains the original configuration (so you don't have to specify it again).
  59. *
  60. * $("...").tableDnDSerialize()
  61. * Will serialize and return the serialized string as above, but for each of the matching tables--so it can be
  62. * called from anywhere and isn't dependent on the currentTable being set up correctly before calling
  63. *
  64. * Known problems:
  65. * - Auto-scoll has some problems with IE7 (it scrolls even when it shouldn't), work-around: set scrollAmount to 0
  66. *
  67. * Version 0.2: 2008-02-20 First public version
  68. * Version 0.3: 2008-02-07 Added onDragStart option
  69. * Made the scroll amount configurable (default is 5 as before)
  70. * Version 0.4: 2008-03-15 Changed the noDrag/noDrop attributes to nodrag/nodrop classes
  71. * Added onAllowDrop to control dropping
  72. * Fixed a bug which meant that you couldn't set the scroll amount in both directions
  73. * Added serialize method
  74. * Version 0.5: 2008-05-16 Changed so that if you specify a dragHandle class it doesn't make the whole row
  75. * draggable
  76. * Improved the serialize method to use a default (and settable) regular expression.
  77. * Added tableDnDupate() and tableDnDSerialize() to be called when you are outside the table
  78. */
  79. jQuery.tableDnD = {
  80. /** Keep hold of the current table being dragged */
  81. currentTable : null,
  82. /** Keep hold of the current drag object if any */
  83. dragObject: null,
  84. /** The current mouse offset */
  85. mouseOffset: null,
  86. /** Remember the old value of Y so that we don't do too much processing */
  87. oldY: 0,
  88. /** Actually build the structure */
  89. build: function(options) {
  90. // Set up the defaults if any
  91. this.each(function() {
  92. // This is bound to each matching table, set up the defaults and override with user options
  93. this.tableDnDConfig = jQuery.extend({
  94. onDragStyle: null,
  95. onDropStyle: null,
  96. // Add in the default class for whileDragging
  97. onDragClass: "tDnD_whileDrag",
  98. onDrop: null,
  99. onDragStart: null,
  100. scrollAmount: 5,
  101. serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
  102. serializeParamName: null, // If you want to specify another parameter name instead of the table ID
  103. dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
  104. }, options || {});
  105. // Now make the rows draggable
  106. jQuery.tableDnD.makeDraggable(this);
  107. });
  108. // Now we need to capture the mouse up and mouse move event
  109. // We can use bind so that we don't interfere with other event handlers
  110. jQuery(document)
  111. .bind('mousemove', jQuery.tableDnD.mousemove)
  112. .bind('mouseup', jQuery.tableDnD.mouseup);
  113. // Don't break the chain
  114. return this;
  115. },
  116. /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
  117. makeDraggable: function(table) {
  118. var config = table.tableDnDConfig;
  119. if (table.tableDnDConfig.dragHandle) {
  120. // We only need to add the event to the specified cells
  121. var cells = jQuery("td."+table.tableDnDConfig.dragHandle, table);
  122. cells.each(function() {
  123. // The cell is bound to "this"
  124. jQuery(this).mousedown(function(ev) {
  125. jQuery.tableDnD.dragObject = this.parentNode;
  126. jQuery.tableDnD.currentTable = table;
  127. jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
  128. if (config.onDragStart) {
  129. // Call the onDrop method if there is one
  130. config.onDragStart(table, this);
  131. }
  132. return false;
  133. });
  134. })
  135. } else {
  136. // For backwards compatibility, we add the event to the whole row
  137. var rows = jQuery("tr", table); // get all the rows as a wrapped set
  138. rows.each(function() {
  139. // Iterate through each row, the row is bound to "this"
  140. var row = jQuery(this);
  141. if (! row.hasClass("nodrag")) {
  142. row.mousedown(function(ev) {
  143. if (ev.target.tagName == "TD") {
  144. jQuery.tableDnD.dragObject = this;
  145. jQuery.tableDnD.currentTable = table;
  146. jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
  147. if (config.onDragStart) {
  148. // Call the onDrop method if there is one
  149. config.onDragStart(table, this);
  150. }
  151. return false;
  152. }
  153. }).css("cursor", "move"); // Store the tableDnD object
  154. }
  155. });
  156. }
  157. },
  158. updateTables: function() {
  159. this.each(function() {
  160. // this is now bound to each matching table
  161. if (this.tableDnDConfig) {
  162. jQuery.tableDnD.makeDraggable(this);
  163. }
  164. })
  165. },
  166. /** Get the mouse coordinates from the event (allowing for browser differences) */
  167. mouseCoords: function(ev){
  168. if(ev.pageX || ev.pageY){
  169. return {x:ev.pageX, y:ev.pageY};
  170. }
  171. return {
  172. x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  173. y:ev.clientY + document.body.scrollTop - document.body.clientTop
  174. };
  175. },
  176. /** Given a target element and a mouse event, get the mouse offset from that element.
  177. To do this we need the element's position and the mouse position */
  178. getMouseOffset: function(target, ev) {
  179. ev = ev || window.event;
  180. var docPos = this.getPosition(target);
  181. var mousePos = this.mouseCoords(ev);
  182. return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
  183. },
  184. /** Get the position of an element by going up the DOM tree and adding up all the offsets */
  185. getPosition: function(e){
  186. var left = 0;
  187. var top = 0;
  188. /** Safari fix -- thanks to Luis Chato for this! */
  189. if (e.offsetHeight == 0) {
  190. /** Safari 2 doesn't correctly grab the offsetTop of a table row
  191. this is detailed here:
  192. http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
  193. the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
  194. note that firefox will return a text node as a first child, so designing a more thorough
  195. solution may need to take that into account, for now this seems to work in firefox, safari, ie */
  196. e = e.firstChild; // a table cell
  197. }
  198. if (e && e.offsetParent) {
  199. while (e.offsetParent){
  200. left += e.offsetLeft;
  201. top += e.offsetTop;
  202. e = e.offsetParent;
  203. }
  204. left += e.offsetLeft;
  205. top += e.offsetTop;
  206. }
  207. return {x:left, y:top};
  208. },
  209. mousemove: function(ev) {
  210. if (jQuery.tableDnD.dragObject == null) {
  211. return;
  212. }
  213. var dragObj = jQuery(jQuery.tableDnD.dragObject);
  214. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  215. var mousePos = jQuery.tableDnD.mouseCoords(ev);
  216. var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
  217. //auto scroll the window
  218. var yOffset = window.pageYOffset;
  219. if (document.all) {
  220. // Windows version
  221. //yOffset=document.body.scrollTop;
  222. if (typeof document.compatMode != 'undefined' &&
  223. document.compatMode != 'BackCompat') {
  224. yOffset = document.documentElement.scrollTop;
  225. }
  226. else if (typeof document.body != 'undefined') {
  227. yOffset=document.body.scrollTop;
  228. }
  229. }
  230. if (mousePos.y-yOffset < config.scrollAmount) {
  231. window.scrollBy(0, -config.scrollAmount);
  232. } else {
  233. var windowHeight = window.innerHeight ? window.innerHeight
  234. : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
  235. if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
  236. window.scrollBy(0, config.scrollAmount);
  237. }
  238. }
  239. if (y != jQuery.tableDnD.oldY) {
  240. // work out if we're going up or down...
  241. var movingDown = y > jQuery.tableDnD.oldY;
  242. // update the old value
  243. jQuery.tableDnD.oldY = y;
  244. // update the style to show we're dragging
  245. if (config.onDragClass) {
  246. dragObj.addClass(config.onDragClass);
  247. } else {
  248. dragObj.css(config.onDragStyle);
  249. }
  250. // If we're over a row then move the dragged row to there so that the user sees the
  251. // effect dynamically
  252. var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
  253. if (currentRow) {
  254. // TODO worry about what happens when there are multiple TBODIES
  255. if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
  256. jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
  257. } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
  258. jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
  259. }
  260. }
  261. }
  262. return false;
  263. },
  264. /** We're only worried about the y position really, because we can only move rows up and down */
  265. findDropTargetRow: function(draggedRow, y) {
  266. var rows = jQuery.tableDnD.currentTable.rows;
  267. for (var i=0; i<rows.length; i++) {
  268. var row = rows[i];
  269. var rowY = this.getPosition(row).y;
  270. var rowHeight = parseInt(row.offsetHeight)/2;
  271. if (row.offsetHeight == 0) {
  272. rowY = this.getPosition(row.firstChild).y;
  273. rowHeight = parseInt(row.firstChild.offsetHeight)/2;
  274. }
  275. // Because we always have to insert before, we need to offset the height a bit
  276. if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
  277. // that's the row we're over
  278. // If it's the same as the current row, ignore it
  279. if (row == draggedRow) {return null;}
  280. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  281. if (config.onAllowDrop) {
  282. if (config.onAllowDrop(draggedRow, row)) {
  283. return row;
  284. } else {
  285. return null;
  286. }
  287. } else {
  288. // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
  289. var nodrop = jQuery(row).hasClass("nodrop");
  290. if (! nodrop) {
  291. return row;
  292. } else {
  293. return null;
  294. }
  295. }
  296. return row;
  297. }
  298. }
  299. return null;
  300. },
  301. mouseup: function(e) {
  302. if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
  303. var droppedRow = jQuery.tableDnD.dragObject;
  304. var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  305. // If we have a dragObject, then we need to release it,
  306. // The row will already have been moved to the right place so we just reset stuff
  307. if (config.onDragClass) {
  308. jQuery(droppedRow).removeClass(config.onDragClass);
  309. } else {
  310. jQuery(droppedRow).css(config.onDropStyle);
  311. }
  312. jQuery.tableDnD.dragObject = null;
  313. if (config.onDrop) {
  314. // Call the onDrop method if there is one
  315. config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
  316. }
  317. jQuery.tableDnD.currentTable = null; // let go of the table too
  318. }
  319. },
  320. serialize: function() {
  321. if (jQuery.tableDnD.currentTable) {
  322. return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
  323. } else {
  324. return "Error: No Table id set, you need to set an id on your table and every row";
  325. }
  326. },
  327. serializeTable: function(table) {
  328. var result = "";
  329. var tableId = table.id;
  330. var rows = table.rows;
  331. for (var i=0; i<rows.length; i++) {
  332. if (result.length > 0) result += "&";
  333. var rowId = rows[i].id;
  334. if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
  335. rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
  336. }
  337. result += tableId + '[]=' + rowId;
  338. }
  339. return result;
  340. },
  341. serializeTables: function() {
  342. var result = "";
  343. this.each(function() {
  344. // this is now bound to each matching table
  345. result += jQuery.tableDnD.serializeTable(this);
  346. });
  347. return result;
  348. }
  349. }
  350. jQuery.fn.extend(
  351. {
  352. tableDnD : jQuery.tableDnD.build,
  353. tableDnDUpdate : jQuery.tableDnD.updateTables,
  354. tableDnDSerialize: jQuery.tableDnD.serializeTables
  355. }
  356. );