drag and drop sortable list of todo items in javascript

To implement drag-and-drop sortable list of todo items in JavaScript, you can use the HTML5 drag and drop API. Here are the basic steps to create a sortable list:

  1. Create an HTML list element to hold the todo items. Each todo item can be an HTML list item (<li>).
  2. Add a draggable attribute to each todo item that should be draggable.
  3. Add event listeners to the todo items to handle drag and drop actions. These events include dragstart, dragenter, dragover, dragleave, and drop.
  4. In the event handlers, update the order of the todo items based on the drag and drop actions.

Here is an example implementation:

<ul id="todo-list">
    <li draggable="true">Item 1</li>
    <li draggable="true">Item 2</li>
    <li draggable="true">Item 3</li>
</ul>
137 chars
6 lines
index.tsx
// Get the todo list element and all the todo items
const todoList = document.getElementById('todo-list');
const todoItems = todoList.querySelectorAll('li');

// Set up the drag and drop event handlers
let draggedItem = null;

todoItems.forEach(item => {
  item.addEventListener('dragstart', e => {
    draggedItem = e.target;
    e.dataTransfer.setData('text/html', draggedItem.outerHTML);
  });

  item.addEventListener('dragenter', e => {
    if (e.target !== draggedItem) {
      e.target.style.opacity = 0.5;
    }
  });

  item.addEventListener('dragover', e => {
    e.preventDefault();
  });

  item.addEventListener('dragleave', e => {
    if (e.target !== draggedItem) {
      e.target.style.opacity = 1;
    }
  });

  item.addEventListener('drop', e => {
    e.preventDefault();
    if (e.target !== draggedItem) {
      const dropzone = e.target.parentNode;
      const droppedItem = document.createElement('li');
      droppedItem.innerHTML = e.dataTransfer.getData('text/html');
      dropzone.replaceChild(droppedItem, e.target);
      dropzone.insertBefore(e.target, draggedItem);
    }
    e.target.style.opacity = 1;
  });
});
1146 chars
42 lines

In this code, we first get the todo list element and all the todo items using document.getElementById and querySelectorAll. Then we loop through the items and add event listeners for the dragstart, dragenter, dragover, dragleave, and drop events.

In the dragstart event handler, we set the draggedItem variable to the current item being dragged and set the data transfer data to the outer HTML of the item.

In the dragenter event handler, we change the opacity of the drop zone to indicate that it's a valid drop target.

In the dragover event handler, we prevent the default dragover behavior to allow dropping.

In the dragleave event handler, we reset the opacity of the drop zone.

In the drop event handler, we prevent the default drop behavior, create a new todo item from the dragged item's outer HTML, replace the dropped item with the new item, and insert the dropped item before the dragged item. Finally, we reset the opacity of the dropped item.

gistlibby LogSnag