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

Leave a Reply

43 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@przemysawbiay3242
24 days ago

Drag and drop starts at 5:17

@francovedia5584
24 days ago

thanks a lot.

@aadhilahamed2581
24 days 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
24 days ago

wow great ..vid

@nguyenviet908
24 days ago

thank you very much <3

@0guerreradelaluz0
24 days 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
24 days 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
24 days ago

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

@ghury1
24 days ago

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

@rotemhoresh
24 days ago

Inspiring.

@christelorsaoure-jf3ne
24 days ago

Thank you Sir

@lucabicego3259
24 days 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
24 days ago

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

@ahabwolf7580
24 days 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
24 days ago

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

@NicoHeinrich
24 days ago

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

@HKbiketravellers
24 days 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
24 days ago

thanks a mill!!! it really helped me 😀

@Trachodil
24 days ago

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

@beckyg5289
24 days ago

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

43
0
Would love your thoughts, please comment.x
()
x