Drag and Drop Sortable List in JavaScript

In this article you will know how to create Drag and Drop Sortable List using JavaScript. I used HTML, CSS and JavaScript to create this JavaScript Drag and Drop Sortable List.

They empower users to effortlessly rearrange items according to their preference, creating a dynamic and interactive interface.

Drag and Drop Sortable List using JavaScript

A Drag and Drop Sortable List in JavaScript refers to a user interface component that allows users to rearrange items in a list by dragging them to new positions. This functionality enhances the user experience by providing an intuitive way to reorder items according to preference or priority.

In this article, if you know basic JavaScript, then you can easily create this project (Drag and Drop Sortable List in JavaScript).

See the Pen Untitled by Growthpanda (@Growthpanda) on CodePen.

As you can see from the preview above, this is a simple Drag and Drop Sortable List in which I have created several lists. You can sort those lists up and down. 

Let’s take a look at how to create a Drag and Drop Sortable List using JavaScript.

Step 1: Structure of Sortable List

First, we will create the basic structure of this Drag and Drop Sortable List by some HTML code.

<div class="container">
    <ul id="list"></ul>
</div>

Step 2: Design the Drag and Drop Sortable List

Next, we apply CSS styling to the list items to enhance visual feedback during the drag and drop process. This may include changes in opacity, cursor style, and positioning.

/* Apply box-sizing: border-box to all elements for consistent box model */
* {
  box-sizing: border-box;
}

/* Reset default margin and padding on the body */
body {
  margin: 0;
  padding: 0;
  background-color: #b5aaf5; /* Set background color for the entire page */
}

/* Style for a container element */
.container {
  font-family: "Poppins", sans-serif; /* Specify the font family */
  background-color: #ffffff; /* Set background color for the container */
  padding: 3em 2em; /* Add padding inside the container */
  width: 90%; /* Set the width of the container to 90% of its parent element */
  max-width: 37em; /* Set the maximum width of the container */
  position: absolute; /* Position the container absolutely */
  transform: translate(-50%, -50%); /* Center the container horizontally and vertically */
  top: 50%; /* Position the container 50% from the top of its containing element */
  left: 50%; /* Position the container 50% from the left of its containing element */
  border-radius: 0.8em; /* Apply border radius to give rounded corners to the container */
}

/* Style for an unordered list element */
#list {
  position: relative; /* Position the list relative to its normal position */
  padding-inline-start: 0; /* Remove default left padding of the list */
  list-style-type: none; /* Remove default list bullet points */
}

/* Style for list items */
.list-item {
  padding: 0.8em 0; /* Add padding to the top and bottom of list items */
  border-radius: 0.2em; /* Apply border radius to give rounded corners to list items */
  margin: 1em auto; /* Center list items horizontally with 1em margin on top and bottom */
  border: 1px solid #000000; /* Add a border around list items */
  text-align: center; /* Center-align text inside list items */
}

/* Style for list items on hover */
.list-item:hover {
  cursor: move; /* Change cursor to indicate draggable */
  background-color: #d1c9ff; /* Change background color on hover */
  border-color: #8673f2; /* Change border color on hover */
  color: #8673f2; /* Change text color on hover */
}

Step 3: JavaScript Code

Finally, we add JavaScript code to enable the drag and drop functionality. This Drag and Drop Sortable List should be activated by JavaScript code.

1. Variable Initialization:
let currentElement = ""; 
let list = document.getElementById("list"); 
let initialX = 0, initialY = 0; 
  • currentElement: Initializes a variable to store the currently dragged element.

  • list: Retrieves a reference to the HTML element with the id “list”, assumed to be a container for draggable items.

  • initialX and initialY: Initialize variables to store the initial mouse/touch coordinates.

2. Function to Check Touch Device:
const isTouchDevice = () => {
  try {
    document.createEvent("TouchEvent"); 
    return true; 
  } catch (e) {
    return false; 
  }
};
  • Defines a function isTouchDevice that tries to create a TouchEvent.

  • If successful, it returns true, indicating the device is a touch device; otherwise, it returns false.

3. Function to Create List Items:
const creator = (count) => {
  for (let i = 1; i <= count; i++) {
    list.innerHTML += `<li class="list-item" data-value="${i}">Item-${i}</li>`;
  }
};
  • Defines a function creator that generates list items within the list container.

  • Each list item is assigned a class list-item and a data-value attribute.

4. Function to Get Position of an Element in the List:
const getPosition = (value) => {
  let elementIndex;
  let listItems = document.querySelectorAll(".list-item");
  listItems.forEach((element, index) => {
    let elementValue = element.getAttribute("data-value");
    if (value == elementValue) {
      elementIndex = index;
    }
  });
  return elementIndex;
};

Defines a function getPosition that retrieves the position (index) of an element in the list based on its data-value attribute.

5. Window Load Event:
window.onload = async () => {
  customElement = "";
  list.innerHTML = "";
  await creator(5); 

  let listItems = document.querySelectorAll(".list-item");
  listItems.forEach((element) => {
    element.draggable = true; 
    element.addEventListener("dragstart", dragStart, false); 
    element.addEventListener("dragover", dragOver, false); 
    element.addEventListener("drop", drop, false); 
    element.addEventListener("touchstart", dragStart, false); 
    element.addEventListener("touchmove", drop, false); 
  });
};
  • When the window loads, it clears the list container, creates 5 list items using the creator function, and attaches event listeners to enable drag and drop functionality for each list item.

  • For touch devices, it also attaches touch event listeners (touchstart and touchmove) to simulate drag and drop functionality.

Drag and Drop Sortable List in JavaScript

Overall, a Drag and Drop Sortable List in JavaScript provides a more engaging and user-friendly way for users to interact with lists of items, allowing them to easily customize the order based on their needs.

Let me know how you like this Drag and Drop Sortable List tutorial by commenting.

Leave a Comment

Home
Menu
Instagram
Search