title: Logic behind drag and drop
body: <p>I am wondering the &quot;how it works&quot; and &quot;how it should be designed and implemented&quot; side of the basic drag &amp; drop functionality.</p>
  <p>I have never yet implemented such functionality. I am planning to do so for one of my projects and I do have some ideas on how to implement it. I wanted to make sure I am on the right path and that you people most probably have something to say about the matter too...</p>
  <p>Let's imagine I have 5 elements listed as following and grabbed from a database;</p>
  <pre><code>&lt;div id=&quot;1&quot;&gt;this is content for 1&lt;/div&gt;
  &lt;div id=&quot;2&quot;&gt;this is content for 2&lt;/div&gt;
  &lt;div id=&quot;3&quot;&gt;this is content for 3&lt;/div&gt;
  &lt;div id=&quot;4&quot;&gt;this is content for 4&lt;/div&gt;
  &lt;div id=&quot;5&quot;&gt;this is content for 5&lt;/div&gt;
  </code></pre>
  <p>since this is pulled off from a database we know that it has a field called &quot;sequence&quot; or &quot;order&quot; to distinguish the order we are going to output. Let's also imagine currently the &quot;sequence&quot; column values are the same as the IDs of the divs. so: <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code> and <code>5</code> respectively.</p>
  <p>My question and thoughts;</p>
  <p>If I drag div <code>4</code> and drop it between <code>1</code> and <code>2</code>; what are the steps from there on? E.g:</p>
  <ol>
  <li><p>determine the id of the div that is being dragged (let's call this <code>div-a</code>)</p>
  </li>
  <li><p>determine the id of the div that  <code>div-a</code> is being inserted after (or before) in this case after and therefore after div <code>id</code> <code>1</code> (let's call this <code>div-b</code>)</p>
  </li>
  <li><p>Update <code>div-a</code>'s sequence in DB and set it to the current sequence of <code>div-b</code></p>
  </li>
  </ol>
  <p>After this step, I am all confused... Do I count all the divs and according to whichever order the divs are, do I update the DB accordingly? Or am I completely wrong and is there another way?</p>
  <hr />
  <p>thanks for the answers but I know there are plugins and other stuff to get this done but I am only interested in the logic part of it.</p>