Reputation: 31
I've searched pretty extensively for an example where someone uses the HTML5 drag and drop API to enable reordering of table rows (tr elements) but there don't seem to be any out there. I have run across some examples which locate the mouse cursor position, but of course these don't leverage the new API events which seem extremely handy.
To date, all I've ever really seen anyone post are examples using ordered and unordered lists and list elements. My own experiments applying dragstart, dragover and drop handlers in a manner similar to how these are used in lists haven't resulted in anything working.
Has anyone managed to apply this to table elements, and do they have a working example? I am aware of the jQuery sortable plugin, but I'm specifically interested in a native JavaScript solution.
Upvotes: 3
Views: 6794
Reputation: 1272
I have spent several days trying to implement HTML 5 drag and drop "from scratch" for React JS based on this tutorial: http://webcloud.se/sortable-list-component-react-js/ and it seems to work fairly well.
Here is what I ended up with: http://jsfiddle.net/LoneIgadzra/wsj7tLw8/
Unfortunately it requires jQuery (although not jQuery UI) for several functions that were a pain to write on my own, namely "closest()" and "offset()". My hope is that this can still get you closer to a working drag-and-drop reorder table. It is not complicated, but there are a TON of gotchas.
All you would need to do is write your own implementations of offset and closest to remove jQuery. The React this.state.data stuff can be replaced with DOM functions to relocate the dragged row on drop.
Honestly, if you can get away with it, just jQuery UI Sortable, works like a charm for tables with very minor tweaks. HTML 5 drag and drop is a horrible API, and less compatible. Here is my working jQuery UI solution that I ditched in favor of React:
jQuery(function($) {
$('table.sortable').sortable({
items: ".item",
axis: "y",
stop: function(event, ui) {
ui.item.effect('highlight');
},
update: function(event, ui) {
// update server here
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<table class="sortable">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr class="item">
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr class="item">
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
<tr class="item">
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table>
Upvotes: 2