JavaScript Sortable Drag and Drop List

02/16/2021

Contents

Demo

Full Screen

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Drag and Drop List</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div id="container">
      <ul id="list" class="list">
        <li class="item" draggable="true">Item01</li>
        <li class="item" draggable="true">Item02</li>
        <li class="item" draggable="true">Item03</li>
        <li class="item" draggable="true">Item04</li>
        <li class="item" draggable="true">Item05</li>
      </ul>
    </div>
    <script src="dragdrop.js"></script>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #242424;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  width: 100%;
  height: 100vh;
  padding: 10px;
}
.list {
  width: 100%;
  max-width: 280px;
}
.item {
  list-style: none;
  width: 100%;
  height: 40px;
  margin: 5px auto;
  padding: 10px;
  background-color: #fff;
  color: #3d3935;
  font-size: 1.25rem;
  text-align: center;
  cursor: move;
}
.active {
  opacity: .5;
}

JavaScript

var list = document.getElementById('list');
var items = document.querySelectorAll('.item');

items.forEach(item => {
  item.addEventListener('dragstart', () => {
    item.classList.add('active');
  });

  item.addEventListener('dragend', () => {
    item.classList.remove('active');
  });
});

list.addEventListener('dragover', (event) => {
  event.preventDefault();
  var afterEl = getAfterEl(list, event.clientY);
  var draggingItem = document.querySelector('.active');
  if(afterEl == null) {
    list.appendChild(draggingItem);
  } else {
    list.insertBefore(draggingItem, afterEl);
  }
});

function getAfterEl(list, y) {
  var draggableEls = [...document.querySelectorAll('.item:not(.active)')];

  return draggableEls.reduce((closest, child) => {
    var box = child.getBoundingClientRect();
    var offset = y - box.top - box.height/2;
    if(offset < 0 && offset > closest.offset) {
      return { offset: offset, element: child };
    } else {
      return closest;
    }
  }, { offset: Number.NEGATIVE_INFINITY }).element;
}