Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To drag drop table rows using Javascript?

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).

like image 569
Harish Kurup Avatar asked Jun 22 '10 07:06

Harish Kurup


People also ask

How do you drag-and-drop rows?

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 do you drag-and-drop elements in Javascript?

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.


2 Answers

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.

like image 76
Fenton Avatar answered Oct 17 '22 21:10

Fenton


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.

like image 2
Garrett Avatar answered Oct 17 '22 21:10

Garrett