Search code examples
javascripthtmlcsshtml-table

How to change the position of an item in a table


I have a simple table like this one:

table, th, td {
  border: 1px black solid;
  border-collapse: collapse;
}
<table>
  <tr>
    <th>number</th>
    <th>name</th>
    <th>id</th>
  </tr>
  <tr>
    <td>1</td>
    <td>red</td>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
    <td>blue</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>yellow</td>
    <td>3</td>
  </tr>
</table>

I want to be able to drag and drop an item from a position to another and change the number of that item to the number of the item it was replaced with but the name and id wouldn't change. for example in the table above I drag blue to the first spot hence the number of blue becomes 1 but blue's id remains 2, and the number of red becomes 2 but red's id remains 1 and their positions in the table also change.

How can I do this?


Solution

  • You can use drag event, when you start draging it make a copy of target you will need it when draging over.

    After the drag ends just reorder the first td in every table row (tr) excluding any row in thead by selecting tbody

    let shadow
    function dragit(event) {
        shadow = event.target;
    }
    function dragover(e) {
        let children = Array.from(e.target.parentNode.parentNode.children);
        if (children.indexOf(e.target.parentNode) > children.indexOf(shadow))
            e.target.parentNode.after(shadow);
        else
            e.target.parentNode.before(shadow);
    }
    function reOrder() {
        document.querySelectorAll(".myTable > tbody > tr > td:first-child").forEach(function (elem, index) {
            elem.innerHTML = (index + 1);
        });
    }
    table, th, td {
        border: 1px black solid;
        border-collapse: collapse;
    }
     <table class="myTable">
        <thead>
            <tr>
                <th>number</th>
                <th>name</th>
                <th>id</th>
            </tr>
        </thead>
        <tbody>
            <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
                <td>1</td>
                <td>red</td>
                <td>1</td>
            </tr>
            <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
                <td>2</td>
                <td>blue</td>
                <td>2</td>
            </tr>
            <tr draggable="true"  ondragstart="dragit(event)"  ondragover="dragover(event)" ondragend="reOrder()">
                <td>3</td>
                <td>yellow</td>
                <td>3</td>
            </tr>
        </tbody>
    </table>