I am using a HTML table to show data, and I want that user can drag and drop the table rows to sort the data as per their need. The HTML code for the table:
<table id='datagrid'>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
</tbody>
</table>
I want that user can drag the rows and sort as per needed... in Javascript NOTE: Don't want answer using jQuery, Mootools or any other Javascript library, because I want to use classic Javascript (i.e. the core).
Drag the rows or columns to another location. Hold down OPTION and drag the rows or columns to another location. Hold down SHIFT and drag your row or column between existing rows or columns. Excel makes space for the new row or column.
How it works: First, select the draggable element using the querySelector() . Second, attach a dragstart event handler to the draggable element. Third, define the dragStart() function to handle the dragstart event.
The reason many people will point you towards a framework is that there are lots of browser differences for drag and drop and the framework handles all of these for you.
However, these event handlers will give you a fair start.
onDragStart - this will fire on the source element when you start to drag it somewhere.
onDrop - this will fire on the target element when you "let go" of the source element while hovering over the target element.
A table row cannot be positioned. There is no way to change the top or left values.
Instead drag a "proxy" element, such as a div.
When the mousedown occurs, if the event target is or contains something you want to drag (its a TR or has a TR ancestor that you care about), show the proxy there and assign a mousemove handler that updates the proxy coordinase.
In the mouseup event, hide the proxy (as stated) and remove the mousemove callback. If the mouseup event occurred in the table, the source TR can be inserted to the new order.
To make the operation more obvious, signifying information from the source TR, such as text inside it, can be copied to the proxy. The source TR can be greyed (by setting opacity or background color).
You might also want to provide some signifier to where the insertion will occur, when the user drops the proxy element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With