Sortable drag and drop list created with HTML CSS & JavaScript | Implementing draggable functionality in JavaScript

Posted by


Drag and drop functionality is a commonly used feature in web development for reordering items on a page. In this tutorial, we will learn how to create a drag and drop sortable list in HTML, CSS, and JavaScript. We will also cover how to make a draggable list in JavaScript.

To start off, let’s create a basic HTML structure for our sortable list:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag and Drop Sortable List</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="sortable-list">
  <div class="list-item">Item 1</div>
  <div class="list-item">Item 2</div>
  <div class="list-item">Item 3</div>
  <div class="list-item">Item 4</div>
</div>
<script src="script.js"></script>
</body>
</html>

In this HTML code, we have a div with the id "sortable-list" containing four list items. Now let’s move on to the CSS to style our list:

#sortable-list {
  width: 300px;
  padding: 10px;
  border: 1px solid #ccc;
}

.list-item {
  background-color: #f9f9f9;
  padding: 10px;
  margin-bottom: 5px;
  cursor: move;
}

This CSS code will style our sortable list by giving it a border, padding, and margin. The list items will have a light gray background color and a cursor indicating they are draggable.

Next, let’s add the JavaScript code to make our list items draggable:

const sortableList = document.getElementById('sortable-list');
let dragItem = null;

sortableList.addEventListener('dragstart', (e) => {
  dragItem = e.target;
  e.dataTransfer.setData('text/plain', null);
});

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

sortableList.addEventListener('drop', (e) => {
  const target = e.target;
  if (target.classList.contains('list-item')) {
    if (target !== dragItem) {
      const rect = target.getBoundingClientRect();
      const next = (e.clientY - rect.top) > rect.height / 2;
      sortableList.insertBefore(dragItem, next ? target.nextElementSibling : target);
    }
  }
});

In this JavaScript code, we are adding event listeners for dragstart, dragover, and drop events to handle the drag and drop functionality. When a list item is dragged, we set it as the dragItem. When the item is dropped over another item, we check if the target is a list item and then determine if it should be placed before or after that target item.

With this code in place, you should now have a basic drag and drop sortable list in your web page. You can customize the styling and functionality further to suit your needs.

I hope this tutorial helps you understand how to create a drag and drop sortable list in HTML, CSS, and JavaScript. Happy coding!

0 0 votes
Article Rating
43 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@przemysawbiay3242
2 months ago

Drag and drop starts at 5:17

@francovedia5584
2 months ago

thanks a lot.

@aadhilahamed2581
2 months ago

I find a correct solution, but couldn't. Finally, I reach your video and I learned the way how it works. Thank you!!!

@shadyether1451
2 months ago

wow great ..vid

@nguyenviet908
2 months ago

thank you very much <3

@0guerreradelaluz0
2 months ago

Thank you very much for that tuto wonderful!
I only have a problem that I can't solve… when I scroll on the page and I try then to order the list, there is a bug.
It doesn't work well and do whatever… 🙁
If someone has a solution. Thx lot.

@user-hc1jl7hn4v
2 months ago

thanks for the tutorial ❤ , you could try to turn down the music a little bit, it gives headache after 5 min straight😥😥

@user-sy2cd2iy4s
2 months ago

What should I do if there is a scroll bar? Can you write an example to support scroll bars?

@ghury1
2 months ago

how to apply this logic if the cards are build dynamically at runtime?

@rotemhoresh
2 months ago

Inspiring.

@christelorsaoure-jf3ne
2 months ago

Thank you Sir

@lucabicego3259
2 months ago

Thank you for you video. Every thing works well except when i will use a scrollable list. In this case the Drag & Drop doesn't work. Can you give me a suggestion on how to manage this situation ? Thanks.

@odunladeoluwaseun7880
2 months ago

What is the best way to store this in a DB?

@ahabwolf7580
2 months ago

I tried this a bit, but ultimately could not get it to correctly position the dragged item where I wanted to drop it in the list. I think it's silly to do the positional calculation when you know you are working with a list of elements like this. You can simply switch your dragover listener to each list item instead of the parent list element (the <ul> in this case), and then just do a few if statements in your listener to check where the current event target (the item you are hovering over) sits in the list in relation to the item you are dragging. That information tells you which direction in the list the item is being dragged, at which point you know if you should be inserting it before or after the item you are over. I believe this also stops the listener from firing hundreds of times while you are dragging? All the rest of this is pretty great though, thanks!

@omarsagr
2 months ago

Thank you for this video.. but it doesn't work on iPhone.. do you have a solution?

@NicoHeinrich
2 months ago

Adding the dragging class after a delay is sooo sneaky. Thanks for sharing!

@HKbiketravellers
2 months ago

Thank you for your video. If the browser length is shorter than the white area, the drag and drop will be shifted by a number of hidden option(s); which makes the codes cannot be used for too many options.

@TheFag
2 months ago

thanks a mill!!! it really helped me 😀

@Trachodil
2 months ago

Hi, how to me get sortable list, so that it can be stored in db. Thanks.

@beckyg5289
2 months ago

Hello, is there a way to add a reset button to this, I am trying but getting some errors, any suggestions?