Have you ever used apps like Trello, Notion, or Asana and wondered how they let you move items around so seamlessly? That smooth drag-and-drop functionality can feel like magic—but it’s something you can create yourself with just a bit of JavaScript.

 In this blog post, we’ll walk through how to build a simple, interactive drag-and-drop list using vanilla JavaScript, no libraries, no frameworks. Whether you’re building a to-do list, a kanban board, or just want to enhance your UI skills, this tutorial will give you a solid foundation in drag-and-drop interaction.

Prerequisites

  • Basic understanding of HTML, CSS, and JavaScript.
  • Browser that supports modern JavaScript.

Let’s jump into the technical part to create a Drag and Drop List:

Step 1: Create the HTML Structure

<ul id="draggable-list">
  <li draggable="true">Item 1</li>
  <li draggable="true">Item 2</li>
  <li draggable="true">Item 3</li>
  <li draggable="true">Item 4</li>
</ul>

Step 2: Add Basic CSS

#draggable-list {
  list-style-type: none;
  width: 300px;
  padding: 0;
}

#draggable-list li {
  padding: 10px;
  background-color: #f1f1f1;
  margin-bottom: 5px;
  border: 1px solid #ccc;
  cursor: move;
}
.dragging {
  opacity: 0.5;
}

Step 3: Add JavaScript for Drag Events

const listItems = document.querySelectorAll('#draggable-list li');
let dragSrcEl = null;

listItems.forEach(item => {
  item.addEventListener('dragstart', function (e) {
    dragSrcEl = this;
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
    this.classList.add('dragging');
  });

  item.addEventListener('dragover', function (e) {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
  });

  item.addEventListener('drop', function (e) {
    e.preventDefault();
    if (dragSrcEl !== this) {
      dragSrcEl.innerHTML = this.innerHTML;
      this.innerHTML = e.dataTransfer.getData('text/html');
    }
  });

  item.addEventListener('dragend', function () {
    this.classList.remove('dragging');
  });
});

Conclusion:

And there you have it—a fully functional drag-and-drop list built with nothing but vanilla JavaScript! This simple project not only enhances user interactivity but also deepens your understanding of core JavaScript concepts like event handling, DOM manipulation, and the HTML5 Drag and Drop API.

The possibilities are endless, and this is just the beginning. Keep experimenting, keep building, and most importantly, keep learning

You may also like this:

Rate this post

Categorized in: