Drag and Drop table content with JavaScript

Content of HTML table cells can be dragged to another cell or another table. It isn’t difficult to define onMouseMove handler and change top / left element styles to move the object. In case with tables, you will have to determine somehow destination cell. Attaching onMouseOver handler on TD elements will not work, because browser doesn’t fire events to the elements beneath the dragged object.

Anyway, after taking care of the current scroll position and calculating TD positions, here is example that should work in FF3+, IE8+, Google Chrome 10+, Safari 5+ and Opera 11+. Click on image below, will open Example 01 with live demo.

Click on image below, will open live demo where you can drag green, blue or orange bordered DIV elements, change properties (radio button and check-boxes) and click on “Save” button.

Download Version 5.1.0 redips2.tar.gz


REDIPS.drag example01

“Save” button will scan table content, create query string and send to the PHP page. Demo shows how to collect content and accept parameters on the server side. More about accepting parameters you can read at Reading multiple parameters in PHP.”Clone” elements (orange in this demo) will be duplicated first because of “redips-clone” keyword contained in class name. If you drop object on cell named “Trash”, object will be deleted from the table (with or without confirmation). Library has built in autoscroll and option to forbid landing to the non empty cells or cells named with class “redips-mark”. Table can contain rowspan / colspan TDs and different background color for every cell.

Here are minimal steps to enable content dragging in table:

  • put <script type=”text/javascript” src=”redips-drag-min.js”></script> to the head section
  • initialize REDIPS.drag library: <body onload=”REDIPS.drag.init()”>
  • place table(s) inside <div id=”redips-drag”> to enable content dragging
  • place <div class=”redips-drag”>Hello World</div> to the table cell

Other features of REDIPS.drag library:

  • functions and data structure are defined in namespace (easier integration with other JS frameworks)
  • JSLint: No problems found in redips-drag-source.js (tough one, huh)
  • REDIPS.drag documentation generated with JsDoc Toolkit
  • drag and drop table rows
  • movable DIV element can contain other HTML code (images, forms, tables …)
  • forbidding or allowing TDs marked with class name “redips-mark”
  • option to define exceptions and allow dropping certain DIV elements to the marked cell
  • option to define single content cell on the table declared with “multiple” drop option
  • cloning
    • for unlimited cloning add “redips-clone” class name to the DIV object
      <div class=”redips-drag redips-clone”>Hello World</div>
    • to limit cloning and transform last object to the ordinary movable object add ‘climit1_X’ class name
      <div class=”redips-drag redips-clone climit1_4″>Hello World</div>
    • to limit cloning and transform last object to immovable object add ‘climit2_X’ class name
      <div class=”redips-drag redips-clone climit2_4″>Hello World</div>
    • where X is integer and defines number of cloned elements (in previous examples, each climit will allow only 4 cloned elements)
  • unlimited nested tables support
  • dropping objects only to empty cells
  • switch cell content
  • switching cell content continuously
  • overwrite TD content with dropped element
  • shift table content
  • table cell with “redips-trash” class name becomes trashcan
  • enabled handlers to place custom code on events: changed, clicked, cloned, clonedDropped, clonedEnd1, clonedEnd2, dblClicked, deleted, dropped, droppedBefore, finish, moved, notCloned, notMoved, shiftOverflow, relocateBefore, relocateAfter, relocateEnd, rowChanged, rowClicked, rowCloned, rowDeleted, rowDropped, rowDroppedBefore, rowDroppedSource, rowMoved, rowNotCloned, rowNotMoved, rowUndeleted, switched and undeleted
  • deleting cloned DIV if the cloned DIV is dragged outside of any table
  • enabling / disabling dragging
  • animation (move element/row to the destination cell/row)
  • added support for touch devices (touchstart, touchmove, touchend)

How REDIPS.drag works?

Script will search for DIV elements (with class name “redips-drag”) inside tables closed in <div id=”redips-drag”> and attach onMouseDown event handler. When user clicks with left mouse button on DIV element, onMouseMove and onMouseUp handlers will be attached to the document level.

While dragging DIV element, script changes its “left” and “top” styles. This is function of the onMouseMove handler. When user releases left mouse button, onMouseUp event handler will unlink onMouseMove and onMouseUp event handlers. This way, browser will listen and process mousemove events only when DIV element is dragged.

As I mentioned, onMouseDown is defined on the elements you want to drag. Elements beneath the dragged object will not be able to catch onMouseOver event. Why? Because you are dragging object and that object only can catch the onMouseOver event.

So, to detect destination table cells, script calculates all cell coordinates (with scroll page offset) and store them to the array. Array is searched inside onMouseMove handler and after left mouse button is released, DIV will drop to the current (highlighted) table cell.

In redips2.tar.gz (160KB) package you will find 27 examples including example of how to save/recall table using PHP and MySQL. Package also contains and redips-drag-min.js – a compressed version of REDIPS.drag library (compressed with Google Closure Compiler).

Happy dragging and dropping!

1,069 thoughts on “Drag and Drop table content with JavaScript

  1. @Ian - your page should work without any additional refresh. Please see

    Example 18: Simple element animation

    ... where you can click on button and move DIV element right after page is loaded. If you have online script (or you can prepare JSFiddle demo) send me an URL and I'll try to find the problem.

  2. Ok here is a link to a test page where I have the problem.
    http://www.nhlguru.net/index4test.php

    It is a pretty complicated page, but it is the "trade" table at the bottom of the page. When you drag and drop a player into the trade area, and click the trade button, he should move to the other side of the table (or one or more players on each side swap places).

    Drag works, but Move does not on 1st page load, but both work on re-load or refresh.
    script4.js is where the redips initialization and the redipsInit.move function are.
    I'm sure its something to do with the way I initialize it, but I've tried everything I can think of!
    Appreciate any help you can provide! Thanks.

  3. @Ian - On the first view, maybe the problem is because you have "min" and "source" lib loading in your page:

    <script type="text/javascript" src="redips-drag-min.js"></script>
    <script type="text/javascript" src="redips-drag-source.js"></script>
    

    Please try to remove line with "redips-drag-source.js" - for production you only need minimized JS file. Hope this will fix the problem, and if not please give me feedback so we can go further.

  4. That didn't do it, but I played with it some more and methodically went over every step.
    Eventually found the problem. During my initial efforts to edit the script for my specific usage, I had at one point deleted the bit of code that gets the start position of the div to be moved.
    So, it wouldn't work unless I refreshed the page, which apparently then got the start position and made the script work. So, for anyone else, don't remove this code :)

    var pos; // current position as array
    pos = REDIPS.drag.getPosition(id); // get start position
    
  5. @Ian - I'm glad you found the problem and now everything works as expected. If you will have any additional questions, please be free to post a comment here.
    Cheers!

  6. I have a problem trying to use their library, I need to select the element, it will double or quadruple the element depending on the case, the draggable area to be detached he was considered a single element, so that every time he is drawn, all the other elements that were created with the first, are drawn together.
    They would also these element were ever cloned from the element of the top, see example I created in stackoverflow.

    http://stackoverflow.com/questions/31107495/working-with-drag-drop-redips

    Excuse the bad English, but do not speak English fluently...

  7. Hello, thank you for redips, it's great!

    I have a question about it. I would like to move two cells as one group. Is it possible?

    I have time table for booking tables in restaurant. Rows are tables, columns are time (hour by hour). I have one reservation for example for 3 hours - 3 cells in same row and I would like to move these 3 cells to another row by one drag&drop.

    Is it possible somehow to group this cells?
    Thank you very much
    Jiri

  8. @Jiri - REDIPS.drag can move only one DIV element at a time. But it's possible to select more elements and with REDIPS.dropped() event, move selected elements as well. Please see the following demo:

    Example 12: Select and move more elements

    Hope this demo will give you an idea how to use event handlers and solve the problem.

Leave a Comment