Advertisement
Guest User

Dylan Marsh

a guest
Feb 20th, 2010
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.  
  80. /*
  81. ** Tweaked slightly for use in FormBuilder project
  82. ** by Dylan Marsh (2-19-10).
  83. */
  84.  
  85. jQuery.tableDnD = {
  86.     /** Keep hold of the current table being dragged */
  87.     currentTable : null,
  88.     /** Keep hold of the current drag object if any */
  89.     dragObject: null,
  90.     /** The current mouse offset */
  91.     mouseOffset: null,
  92.     /** Remember the old value of Y so that we don't do too much processing */
  93.     oldY: 0,
  94.  
  95.     /** Actually build the structure */
  96.     build: function(options) {
  97.         // Set up the defaults if any
  98.  
  99.         this.each(function() {
  100.             // This is bound to each matching table, set up the defaults and override with user options
  101.             this.tableDnDConfig = jQuery.extend({
  102.                 onDragStyle: null,
  103.                 onDropStyle: null,
  104.                 // Add in the default class for whileDragging
  105.                 onDragClass: "tDnD_whileDrag",
  106.                 onDrop: null,
  107.                 onDragStart: null,
  108.                 scrollAmount: 5,
  109.                 serializeRegexp: /[^\-]*$/, // The regular expression to use to trim row IDs
  110.                 serializeParamName: null, // If you want to specify another parameter name instead of the table ID
  111.                 dragHandle: null // If you give the name of a class here, then only Cells with this class will be draggable
  112.             }, options || {});
  113.             // Now make the rows draggable
  114.             jQuery.tableDnD.makeDraggable(this);
  115.         });
  116.  
  117.         // Now we need to capture the mouse up and mouse move event
  118.         // We can use bind so that we don't interfere with other event handlers
  119.         jQuery(document)
  120.             .bind('mousemove', jQuery.tableDnD.mousemove)
  121.             .bind('mouseup', jQuery.tableDnD.mouseup);
  122.  
  123.         // Don't break the chain
  124.         return this;
  125.     },
  126.  
  127.     /** This function makes all the rows on the table draggable apart from those marked as "NoDrag" */
  128.     makeDraggable: function(table) {
  129.         var config = table.tableDnDConfig;
  130.         if (table.tableDnDConfig.dragHandle) {
  131.             // We only need to add the event to the specified cells
  132.             //var cells = jQuery("td . " + table.tableDnDConfig.dragHandle, table);
  133.             var cells = jQuery("th." + table.tableDnDConfig.dragHandle, table);   // dylan -- use TH as dragHandle (instead of TH)
  134.            
  135.             cells.each(function()
  136.             {
  137.                 // The cell is bound to "this"
  138.                 jQuery(this).mousedown(function(ev)
  139.                 {
  140.                       jQuery.tableDnD.dragObject = this.parentNode;
  141.                       jQuery.tableDnD.currentTable = table;
  142.                       jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
  143.                      
  144. @@                    /*
  145. @@                    ** Only call onDragStart if
  146. @@                    ** mouse moves > 2px (on Y)
  147. @@                    */
  148. @@                    if(config.onDragStart)
  149. @@                    {
  150. @@                          var startOffset = jQuery.tableDnD.mouseOffset.y;
  151. @@                         
  152. @@                          jQuery(this).bind("mousemove", function(ev)
  153. @@                          {
  154. @@                              var newOffset = jQuery.tableDnD.getMouseOffset(this, ev).y;
  155. @@                             
  156. @@                              if(newOffset > startOffset + 2 || newOffset < startOffset - 2)
  157. @@                              {
  158. @@                                  config.onDragStart(table, this);   // Call onDragStart callback
  159. @@                              }
  160. @@                          });
  161. @@                    }
  162.                      
  163.                       return false;
  164.                  });
  165.                
  166.                 // Unbind mousemove on mouseup / mouseleave
  167.                 jQuery(this).bind("mouseup", function() { jQuery(this).unbind("mousemove") });
  168.                 jQuery(this).bind("mouseleave", function() { jQuery(this).unbind("mousemove") })
  169.             })
  170.            
  171.            
  172.         } else {
  173.             // For backwards compatibility, we add the event to the whole row
  174.             var rows = jQuery("tr", table); // get all the rows as a wrapped set
  175.             rows.each(function() {
  176.                 // Iterate through each row, the row is bound to "this"
  177.                 var row = jQuery(this);
  178.                 if (! row.hasClass("nodrag")) {
  179.                     row.mousedown(function(ev) {
  180.                               if (ev.target.tagName == "TD") {
  181.                         //if (ev.target.tagName == "TD" || ev.target.tagName == "TH") {   // dylan (10-27-09)
  182.                             jQuery.tableDnD.dragObject = this;
  183.                             jQuery.tableDnD.currentTable = table;
  184.                             jQuery.tableDnD.mouseOffset = jQuery.tableDnD.getMouseOffset(this, ev);
  185.                             if (config.onDragStart) {
  186.                                 // Call the onDrop method if there is one
  187.                                 config.onDragStart(table, this);
  188.                             }
  189.                             return false;
  190.                         }
  191.                     }).css("cursor", "move"); // Store the tableDnD object
  192.                 }
  193.             });
  194.         }
  195.     },
  196.  
  197.     updateTables: function() {
  198.         this.each(function() {
  199.             // this is now bound to each matching table
  200.             if (this.tableDnDConfig) {
  201.                 jQuery.tableDnD.makeDraggable(this);
  202.             }
  203.         })
  204.     },
  205.  
  206.     /** Get the mouse coordinates from the event (allowing for browser differences) */
  207.     mouseCoords: function(ev){
  208.         if(ev.pageX || ev.pageY){
  209.             return {x:ev.pageX, y:ev.pageY};
  210.         }
  211.         return {
  212.             x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
  213.             y:ev.clientY + document.body.scrollTop  - document.body.clientTop
  214.         };
  215.     },
  216.  
  217.     /** Given a target element and a mouse event, get the mouse offset from that element.
  218.         To do this we need the element's position and the mouse position */
  219.     getMouseOffset: function(target, ev) {
  220.         ev = ev || window.event;
  221.  
  222.         var docPos    = this.getPosition(target);
  223.         var mousePos  = this.mouseCoords(ev);
  224.         return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
  225.     },
  226.  
  227.     /** Get the position of an element by going up the DOM tree and adding up all the offsets */
  228.     getPosition: function(e){
  229.         var left = 0;
  230.         var top  = 0;
  231.         /** Safari fix -- thanks to Luis Chato for this! */
  232.         if (e.offsetHeight == 0) {
  233.             /** Safari 2 doesn't correctly grab the offsetTop of a table row
  234.             this is detailed here:
  235.             http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
  236.             the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
  237.             note that firefox will return a text node as a first child, so designing a more thorough
  238.             solution may need to take that into account, for now this seems to work in firefox, safari, ie */
  239.             e = e.firstChild; // a table cell
  240.         }
  241.  
  242.         while (e.offsetParent){
  243.             left += e.offsetLeft;
  244.             top  += e.offsetTop;
  245.             e     = e.offsetParent;
  246.         }
  247.  
  248.         left += e.offsetLeft;
  249.         top  += e.offsetTop;
  250.  
  251.         return {x:left, y:top};
  252.     },
  253.  
  254.     mousemove: function(ev) {
  255.         if (jQuery.tableDnD.dragObject == null) {
  256.             return;
  257.         }
  258.  
  259.         var dragObj = jQuery(jQuery.tableDnD.dragObject);
  260.         var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  261.         var mousePos = jQuery.tableDnD.mouseCoords(ev);
  262.         var y = mousePos.y - jQuery.tableDnD.mouseOffset.y;
  263.         //auto scroll the window
  264.         var yOffset = window.pageYOffset;
  265.         if (document.all) {
  266.             // Windows version
  267.             //yOffset=document.body.scrollTop;
  268.             if (typeof document.compatMode != 'undefined' &&
  269.                  document.compatMode != 'BackCompat') {
  270.                yOffset = document.documentElement.scrollTop;
  271.             }
  272.             else if (typeof document.body != 'undefined') {
  273.                yOffset=document.body.scrollTop;
  274.             }
  275.  
  276.         }
  277.            
  278.         if (mousePos.y-yOffset < config.scrollAmount) {
  279.             window.scrollBy(0, -config.scrollAmount);
  280.         } else {
  281.             var windowHeight = window.innerHeight ? window.innerHeight
  282.                     : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
  283.             if (windowHeight-(mousePos.y-yOffset) < config.scrollAmount) {
  284.                 window.scrollBy(0, config.scrollAmount);
  285.             }
  286.         }
  287.  
  288.  
  289.         if (y != jQuery.tableDnD.oldY) {
  290.             // work out if we're going up or down...
  291.             var movingDown = y > jQuery.tableDnD.oldY;
  292.             // update the old value
  293.             jQuery.tableDnD.oldY = y;
  294.             // update the style to show we're dragging
  295.             if (config.onDragClass) {
  296.                 dragObj.addClass(config.onDragClass);
  297.             } else {
  298.                 dragObj.css(config.onDragStyle);
  299.             }
  300.             // If we're over a row then move the dragged row to there so that the user sees the
  301.             // effect dynamically
  302.             var currentRow = jQuery.tableDnD.findDropTargetRow(dragObj, y);
  303.             if (currentRow) {
  304.                 // TODO worry about what happens when there are multiple TBODIES
  305.                 if (movingDown && jQuery.tableDnD.dragObject != currentRow) {
  306.                     jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow.nextSibling);
  307.                 } else if (! movingDown && jQuery.tableDnD.dragObject != currentRow) {
  308.                     jQuery.tableDnD.dragObject.parentNode.insertBefore(jQuery.tableDnD.dragObject, currentRow);
  309.                 }
  310.             }
  311.         }
  312.  
  313.         return false;
  314.     },
  315.  
  316.     /** We're only worried about the y position really, because we can only move rows up and down */
  317.     findDropTargetRow: function(draggedRow, y) {
  318.         var rows = jQuery.tableDnD.currentTable.rows;
  319.         for (var i=0; i<rows.length; i++) {
  320.             var row = rows[i];
  321.             var rowY    = this.getPosition(row).y;
  322.             var rowHeight = parseInt(row.offsetHeight)/2;
  323.             if (row.offsetHeight == 0) {
  324.                 rowY = this.getPosition(row.firstChild).y;
  325.                 rowHeight = parseInt(row.firstChild.offsetHeight)/2;
  326.             }
  327.             // Because we always have to insert before, we need to offset the height a bit
  328.             if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
  329.                 // that's the row we're over
  330.                 // If it's the same as the current row, ignore it
  331.                 if (row == draggedRow) {return null;}
  332.                 var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  333.                 if (config.onAllowDrop) {
  334.                     if (config.onAllowDrop(draggedRow, row)) {
  335.                         return row;
  336.                     } else {
  337.                         return null;
  338.                     }
  339.                 } else {
  340.                     // If a row has nodrop class, then don't allow dropping (inspired by John Tarr and Famic)
  341.                     var nodrop = jQuery(row).hasClass("nodrop");
  342.                     if (! nodrop) {
  343.                         return row;
  344.                     } else {
  345.                         return null;
  346.                     }
  347.                 }
  348.                 return row;
  349.             }
  350.         }
  351.         return null;
  352.     },
  353.  
  354.     mouseup: function(e) {
  355.         if (jQuery.tableDnD.currentTable && jQuery.tableDnD.dragObject) {
  356.             var droppedRow = jQuery.tableDnD.dragObject;
  357.             var config = jQuery.tableDnD.currentTable.tableDnDConfig;
  358.             // If we have a dragObject, then we need to release it,
  359.             // The row will already have been moved to the right place so we just reset stuff
  360.             if (config.onDragClass) {
  361.                 jQuery(droppedRow).removeClass(config.onDragClass);
  362.             } else {
  363.                 jQuery(droppedRow).css(config.onDropStyle);
  364.             }
  365.             jQuery.tableDnD.dragObject   = null;
  366.             if (config.onDrop) {
  367.                 // Call the onDrop method if there is one
  368.                 config.onDrop(jQuery.tableDnD.currentTable, droppedRow);
  369.             }
  370.             jQuery.tableDnD.currentTable = null; // let go of the table too
  371.         }
  372.     },
  373.  
  374.     serialize: function() {
  375.         if (jQuery.tableDnD.currentTable) {
  376.             return jQuery.tableDnD.serializeTable(jQuery.tableDnD.currentTable);
  377.         } else {
  378.             return "Error: No Table id set, you need to set an id on your table and every row";
  379.         }
  380.     },
  381.  
  382.     serializeTable: function(table) {
  383.         var result = "";
  384.         var tableId = table.id;
  385.         var rows = table.rows;
  386.         for (var i=0; i<rows.length; i++) {
  387.             if (result.length > 0) result += "&";
  388.             var rowId = rows[i].id;
  389.             if (rowId && rowId && table.tableDnDConfig && table.tableDnDConfig.serializeRegexp) {
  390.                 rowId = rowId.match(table.tableDnDConfig.serializeRegexp)[0];
  391.             }
  392.  
  393.             result += tableId + '[]=' + rowId;
  394.         }
  395.         return result;
  396.     },
  397.  
  398.     serializeTables: function() {
  399.         var result = "";
  400.         this.each(function() {
  401.             // this is now bound to each matching table
  402.             result += jQuery.tableDnD.serializeTable(this);
  403.         });
  404.         return result;
  405.     }
  406.  
  407. }
  408.  
  409. jQuery.fn.extend(
  410.     {
  411.         tableDnD : jQuery.tableDnD.build,
  412.         tableDnDUpdate : jQuery.tableDnD.updateTables,
  413.         tableDnDSerialize: jQuery.tableDnD.serializeTables
  414.     }
  415. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement