title: How to limit a div inside its container after a drag?
body: <p>I would like to drag a div inside the bounds of its container, I don't manage to limit the drag cursor (the orange div) inside the limit of its container : it goes too much on the right when it is on the left and the right borders. 
  Here is the JsFiddle : <a href="https://jsfiddle.net/k2dc8p8c/" rel="nofollow noreferrer">https://jsfiddle.net/k2dc8p8c/</a><br>
  and the code :</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;title&gt;Page Title&lt;/title&gt;
  &lt;style media="screen"&gt;
  body{
    width: 1500px; height: 1500px;
  }
    #container{
      position:absolute;
      width: 300px; height: 80px; border: 1px solid red;
    }
    #cursor{
      position:absolute;
      width: 50px; height:100%;
      background-color: orange;
    }
    .dontSelect{
      -webkit-user-select: none;
      -moz-user-select: none;
      -o-user-select: none;
      -ms-user-select: none;
      -khtml-user-select: none;
      user-select: none;
    }
  &lt;/style&gt;
  &lt;/head&gt;
  &lt;body&gt;
  
  &lt;div id="container" class="dontSelect"&gt;
    &lt;div id="cursor" class="dontSelect"&gt;&lt;/div&gt;
  &lt;/div&gt;
  
  &lt;script&gt;
  var cursor = document.getElementById("cursor");
  var container = document.getElementById("container");
  var isMouseDown = false;
  var w = container.offsetWidth, startPosClick = 0;
  var leftContainerStart = container.offsetLeft;
  cursor.style.left = leftContainerStart + (w/2) - (cursor.offsetWidth/2)+"px";
  var leftCursorStart = cursor.offsetLeft;
  //events
  document.body.addEventListener("mousemove", function(e){
    if (isMouseDown){
      var dx = e.clientX - startPosClick;//*** HERE ***
      if (dx + leftCursorStart &gt; 0 &amp;&amp; (leftCursorStart + dx) &lt; (leftContainerStart+w-cursor.offsetWidth)){
        cursor.style.left = dx+leftCursorStart+"px";
      }
    }
  });
  cursor.addEventListener("mousedown", function(e){
    isMouseDown = true;
    startPosClick = e.clientX;
    leftCursorStart = cursor.offsetLeft;
  });
  document.body.addEventListener("mouseup", function(){
    isMouseDown = false;
  });
  
  &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Thanks</p>