Draggable div with jQuery – not working perfectly

I have created a simple draggable div and its working somewhat good but when I try to drag it the mouse cursor is jumping, what is wrong here?

var $dragging = null;
$(document.body).on("mousemove", function(e) {
  if ($dragging) {
    $dragging.offset({
      top: e.pageY,
      left: e.pageX
    });
  }
});
$(document.body).on("mousedown", ".titleDraggble", function (e) {
  $dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
  $dragging = null;
});
.titleDraggble {
  width: 40px;
  height: 40px;
  position: absolute;
  left: 20px;
  top: 20px;
  border: 1px solid #000;
  cursor: move;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titleDraggble"></div>

Answer

If you want to prevent the mouse cursor from jumping, you must take into account the offset of the mouse in relation to the target element.

var $dragging = null;
var offsetx = null;
var offsety = null;

$(document.body).on("mousemove", function(e) {
  if ($dragging) {
    $dragging.offset({
      top: e.pageY - offsety,
      left: e.pageX - offsetx
    });
  }
});
$(document.body).on("mousedown", ".titleDraggble", function (e) {
  var rect = e.target.getBoundingClientRect();
  offsetx = e.clientX - rect.left;
  offsety = e.clientY - rect.top;
  $dragging = $(e.target);
});
$(document.body).on("mouseup", function (e) {
  $dragging = null;
});
.titleDraggble {
  width: 40px;
  height: 40px;
  position: absolute;
  left: 20px;
  top: 20px;
  border: 1px solid #000;
  cursor: move;
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="titleDraggble"></div>