Drag and Drop table content with JavaScript

More...

Content of HTML table cells can be dragged to another table 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 table cell. Attaching onMouseOver handler on table cells 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 table cells positions, here is example that should work in FF3, IE8, Google Chrome, Safari 5 and Opera 11. Please try to drag green, blue or orange bordered DIV elements, change properties (radio button and check-boxes) and click on "Save" button.
Version 4.6.6
Download redips2.tar.gz
You can not drop here
Drag
and
drop
content
with
JavaScript
Smile
Table2
and
Drag
drop
table
with
JavaScript
Table3
Clone
(1) Clone
(2) Clone
Trash
Save content of the first table (it will only show accepted parameters)
Enable dropping to already taken table cells
Disable dropping to already taken table cells
Switch content
Switching content continuously
Overwrite content
Remove cloned object if dragged outside of any table
Delete confirmation
Enable dragging

"Save" button will scan tables, create query string and send to the PHP page. Demo shows how to collect table content and accept parameters on the server side. More about accepting parameters you can read in my post Reading multiple parameters in PHP."Clone" elements (orange in this demo) will be duplicated first because of "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). Script has built in autoscroll and option to forbid landing to non empty cells or cells named with class "forbid". Table can contain rowspan / colspan cells 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="drag"> to enable content dragging
  • place <div class="drag">Hello World</div> to the table cell

Other features of redips-drag.js:

  • functions and data structure are defined in namespace (easier integration with other JS frameworks)
  • JSLint: No problems found in redips-drag.js (tough one, huh)
  • REDIPS.drag documentation generated with JsDoc Toolkit
  • drag and drop table rows
  • movable div element can contain form elements, images and links
  • forbidding or allowing table cells marked with class name "mark" (depends on "marked_cell" parameter)
  • option to define exceptions and allow certain DIV elements to the marked table cell
  • option to define single content cell on the table declared with "multiple" drop option
  • cloning
    • for unlimited cloning add "clone" class name to the div object
      <div class="drag clone">Hello World</div>
    • to limit cloning and transform last object to the ordinary movable object add 'climit1_X' class name
      <div class="drag clone climit1_4">Hello World</div>
    • to limit cloning and transform last object to immovable object add 'climit2_X' class name
      <div class="drag 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 table content
  • switching content continuously
  • overwrite table cell content with dropped element
  • shift table content
  • table cell with "trash" class name becomes trashcan
  • enabled handlers to place custom code on events: clicked, moved, not moved, dropped, switched, changed, cloned, cloned end1, cloned end2, not cloned, deleted 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.js works?

Script will search for div elements (with class name "drag") inside tables closed in <div id="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 "left" and "top" styles of the object. 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 user holds left mouse button on div element.

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 table cell coordinates (with scroll page offset) and store them to arrays. Arrays are searched inside onMouseMove handler and after left mouse button is released, object will drop to the current (highlighted) table cell.

In redips2.tar.gz (118KB) package you will find 21 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.

Happy dragging and dropping!

This entry was posted on April 6, 2009 and is filed under Drag and Drop, JavaScript

Related posts

678 Responses to Drag and Drop table content with JavaScript

  1. Filip says:

    I think there is a bug in Mobile Safari (iOS 4.3.3 as well as 5.0.1). Once an element is dragged (or after being cloned), it cannot be dragged again.
    A dirty solution is to call init() after each drop.

  2. Renkor says:

    hi dbunic... I'm sorry, but I can not solve other problems ... when I load objects from DB to table I create new div with a id 1c0, 1c1 ... When I copy the same object from the "toolbar" once again it creates a copy of the initial (0) and I also fail to apply clone limit on it. Maybe solution should be to call a copy function and give there required properties and position, but I don't know how. Thanks for your time. Renkor

  3. dbunic says:

    @glwilliams4 - To change border of current table cell please take a look to Drag and drop table rows with JavaScript example. It's a bit tricky to change cell border in case of table border-collapse (I wrote a comment in example15/style.css) but it's possible.

    @Filip - Yes, in a moment when DIV element is moved, registration of event listeners are lost in Safari Mobile browser (I saw it on a friend's IPhone). So, after element is moved it becomes unmovable(?!) Anyway, thank you for pointing to the problem. I will have to make more tests to see where is the problem. Any help in further diagnosis is more than welcome.

    @Renkor - If the problem is related to conflict between DIV elements retrieved from database and cloned on table maybe you can generate different id for database elements. I had similar situation in example03 (School timetable). Please open example03/config.php and see around line 92 ... In short, cloned elements will have added c1, c2, c3 suffix to id of source element. In a moment when cloned element will be saved to the database you can detach id to original part and cloned part. This way, different id can be prepared for cloned elements retrieved from database. Lets say source element have id="aa". Cloned elements will have id="aac1", id="aac2", id="aac3" ... Before saving to database you can cut c1, c2, c3 suffix and save only "aa". In a moment of displaying DIV element on page, id can be composed of "aa" and lets say "b1" , "b2", "b3" so there will not be conflict between new cloned elements and elements displayed from database ("aab1", "aab2" ...). Saving "aab1" will also cut "b1" suffix and save only "aa" to the database (with defined table position). The same logic is used in example03.

  4. Renkor says:

    Thank you for the quick reply, I had this solution yesterday and maybe it's best idea. But I can not solve the problem with clone Limit. When it upload elements of DB and then give them another ID (instead of 11c1 it create 11) need to be covered by the same limit as the basic elements. For example: I create element from the DB (Power_source_b0) and it may be in area ​​only one ... so that can not be created new (Power_source), but after delete I need to permit to create new one... Thanks Renkor

  5. Renkor says:

    sorry for my next message but maybe I have an idea how to solve this problem. Easy soulution should be disable possibility of cloning and deleting these elements... Then I can create these element once on area where they can be only draged, saved and loaded from DB... But how to create irremovable element? Thanks Renkor

  6. WolveFred says:

    Hi,

    Great script !

    One question : is it possible to make the clickable zone for drag smaller than the draggable zone ?

    I mean : I want to make only a small portion of a div able to be clicked for moving the whole div elsewhere.

    Is it possible and how ?

    Thanks at advance.

  7. dbunic says:

    @Renkor - Element can be disabled in script (more examples are in documentation):

    // disable element with id="id123"
    rd.enable_drag(false, 'id123');
    

    or remove class "drag" in case of displaying elements from database.

    @WolveFred - DIV element with class="drag" is container and listens for onclick event on its whole surface. Unfortunately, REDIPS.drag library currently doesn't have option to define smaller clickable zone but it can be shown like it has. Please see Example 11: Drag handle on titlebar. Actually it only changes cursor (from "move" to "default") but you can click on DIV element anywhere to drag it around. I know it's not a clean solution but maybe it can help.

  8. WolveFred says:

    Thanks for your answer.

    Maybe I have a solution and I will test it later :
    - Make the panel not dragable.
    - When the user clicks and hold on the small button of the panel, we make the whole panel dragable.
    - When the user release the mouse click, so the panel becomes not dragable again.

  9. Nivas says:

    Hi,

    My requirement is, The element should be drag and drop in the same Table, But When I try to drag it to another table, it should not. How can I achieve this?

    Thanks,
    Nivas

  10. WolveFred says:

    @Nivas : It is easy : set the id "drag" for the table that autorize drag and drop, and set nothing for the other table. It implies that the second table is not nested inside the first.

  11. dbunic says:

    @WolveFred - Sounds nice - hope it will work and thanks for helping others.

    @Nivas - The easiest way is to create separated drag containers like in Example 8: Tables in separated containers. Just peek to the source. Here is code snippet of how to initialize each DIV container:

    // reference to the REDIPS.drag class
    var rd = REDIPS.drag;
    // DIV container initialization
    rd.init('drag1');
    rd.init('drag2');
    
  12. WolveFred says:

    @dbunic : Yes that works now ! Thank you !

  13. Lakshman says:

    Hi,

    In my case, i know row, col and table number and i want to get id of the cell (ie., i know position of my cell, but not the id of the element) Is there any method available to get id of div element ?

    if not can you please let me know, how can we achieve this?

  14. dbunic says:

    @Lakshman - REDIPS.drag doesn't have such method but here is JS code that might help you:

    // display Id of first DIV element inside table cell with coordinates
    // tableIndex, rowIndex and cellIndex
    function displayId(tableIndex, rowIndex, cellIndex) {
        // define local variables
        var tables, cell, div;
        // get tables inside REDIPS.drag container
        // (this can be globally set to skip possible overhead)
        tables = document.getElementById('drag').getElementsByTagName('table');
        // set reference to the table cell
        cell = tables[tableIndex].rows[rowIndex].cells[cellIndex];
        // mark cell to become visible (just for testing purpose)
        cell.style.backgroundColor = 'lime';
        // get references of DIV element(s) inside table cell
        div = cell.getElementsByTagName('div');
        // test if there is any DIV element
        if (div.length > 0) {
            // display Id of first DIV element
            alert(div[0].id);
        }
    }
    

    ... and how to use it:

    // display DIV Id for first table, third row and third column (cell)
    displayId(0, 2, 2);
    
  15. Lakshman says:

    @dbunic, first of all thank you for immediate response, the solution you have given will be very much useful.

    I have one more question, I have two tables (say table1 & table2) and in JavaScript I have set:

    rd.drop_option = 'switch';
    

    What I want is, if I click on any element in table1, certain cells in table2 (not all elements only certain DIV elements with some specific id) should be disabled and should not allow to swap the content even though cell choosed from table1 is dropped on these elements.

    Issue I am facing is: as drop option is set to switch, even though cell is set to disabled, after dropping the element from table1 on disabled cell of table2 is swapping the elements.

    Can you please suggest me, Is there any way to achieve this?

  16. dbunic says:

    @Lakshman - drop_option can be dynamically changed. Please see Example 9: Single and shift mode. Here is code snippet from that example:

    // in a moment when DIV element is moved, set drop_option (shift or single)
    rd.myhandler_moved = function () {
        // find parent table of moved element
        var tbl = rd.find_parent('TABLE', rd.obj);
        // if table id is table1
        if (tbl.id === 'table1') {
            rd.drop_option = 'shift';
        }
        else {
            rd.drop_option = 'single';
        }
    };
    

    On the similar way you can test DIV element id and set "switch" or "multiple" option:

    rd.myhandler_moved = function () {
        // set DIV element id
        var id = rd.obj.id;
        ...
    
  17. dman says:

    Thanks for the library.

    Two quick questions:
    1) is it possible to dynamically generate new table elements without user interaction?

    2) is it possible to have two [div id="drag"] sections on the page? When I do that only one is active.

    Thanks

  18. dbunic says:

    1)
    Yes, it's possible to create a new DIV element and place it manually to the table. New DIV element should contain drag class name. After element is added to the table it should be "enabled" - please see documentation for enable_drag() method.

    2)
    REDIPS.drag library can have many separated drag containers like in example08 - Tables in separated containers. Elements from first container can't be dropped to the second container and vice versa. If you want to disable all elements in a table, that can be done with enable_table() method. So with using event handlers, enable/disable (toggle) table elements should not be a problem.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>