title: How to make smooth sortable drag and drop?
body: <p>I have create a code for sorting a list of word in possible order it does sort but sometime it just behave very nicely.</p>
  <p>I have took the horizontal coordinate of mouse event and then using this calculated the offset for better position.</p>
  <p>Do i need to add any this else into or something I am missing in my calculation for offset</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>const draggables = document.querySelectorAll('.draggable')
  const containers = document.querySelectorAll('.container')
  
  draggables.forEach(draggable =&gt; {
    draggable.addEventListener('dragstart', () =&gt; {
      draggable.classList.add('dragging')
    })
  
    draggable.addEventListener('dragend', () =&gt; {
      draggable.classList.remove('dragging')
    })
  })
  
  containers.forEach(container =&gt; {
    container.addEventListener('dragover', e =&gt; {
      e.preventDefault()
      const afterElement = getDragAfterElement(container, e.clientX)
      const draggable = document.querySelector('.dragging')
      if (afterElement == null) {
        container.appendChild(draggable)
      } else {
        container.insertBefore(draggable, afterElement)
      }
    })
  })
  
  function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
  
    return draggableElements.reduce((closest, child) =&gt; {
      const box = child.getBoundingClientRect()
      const offset = y - box.right - box.width / 2
      if (offset &lt; 0 &amp;&amp; offset &gt; closest.offset) {
        return { offset: offset, element: child }
      } else {
        return closest
      }
    }, { offset: Number.NEGATIVE_INFINITY }).element
  }</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
    background-color: #333;
    padding: 1rem;
    margin-top: 1rem;
  }
  
  .draggable {
    display: inline-flex;
    padding: 1rem;
    background-color: white;
    border: 1px solid black;
    cursor: move;
    margin: 0.4rem;
  }
  
  .draggable.dragging {
    opacity: .5;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="container"&gt;
    &lt;span class="draggable" draggable="true"&gt;every  &lt;/span&gt;
    &lt;span class="draggable" draggable="true"&gt;so&lt;/span&gt;
    &lt;span class="draggable" draggable="true"&gt;beautiful&lt;/span&gt;
    &lt;span class="draggable" draggable="true"&gt;thing&lt;/span&gt;
    &lt;span class="draggable" draggable="true"&gt;is&lt;/span&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>