0

I am writing a drag & drop script for dragging and dropping blocks with a class '.draggable'. The problem is that periodically the block sticks to the cursor and does not come off. How to edit this script so that all blocks with a class '.draggable' can be dragged with the mouse without this problem?

let elements = document.querySelectorAll('.draggable');

elements.forEach(function(el) {
  let mover = false,
    x, y, posx, posy, first = true;
  el.onmousedown = function() {
    mover = true;
  };
  el.onmouseup = function() {
    mover = false;
    first = true;
  };
  el.parentNode.onmousemove = function(e) {
    el.style.cursor = "move";
    if (mover) {
      if (first) {
        x = e.offsetX;
        y = e.offsetY;
        first = false;
      }

      posx = e.pageX - x;
      posy = e.pageY - y;
      el.style.left = posx + 'px';
      el.style.top = posy + 'px';
    }
  }
});
.draggable {
  position: absolute;
  z-index: 1;
  top: 100px;
}
<section class="dragscroll">
  <div class="draggable">
    <textarea></textarea>
   </div>
</section>

<section class="dragscroll">
  <div class="draggable">
    <textarea></textarea>
  </div>
</section>
All In
  • 89
  • 1
  • 6
  • 1
    Possible duplicate of this: https://stackoverflow.com/questions/3831589/losing-mouseup-event-if-releasing-not-over-the-same-element https://stackoverflow.com/questions/9506041/events-mouseup-not-firing-after-mousemove Your mouseup is not firing when the cursor is moving out of current element – Parikshith Kedilaya M Dec 16 '20 at 19:11

1 Answers1

1

Its difficult to say that this works as its difficult to produce the bug, so please let me know it this works. All I did was

document.addEventListener("mouseup", function() {
    mover = false;
    first = true;
  });

let elements = document.querySelectorAll('.draggable');

elements.forEach(function(el) {
  let mover = false,
    x, y, posx, posy, first = true;
  el.onmousedown = function() {
    mover = true;
  };
  document.addEventListener("mouseup", function() {
    mover = false;
    first = true;
  });
/*
  document.onmouseup = function() {
    mover = false;
    first = true;
  };
*/
  el.parentNode.onmousemove = function(e) {
    el.style.cursor = "move";
    if (mover) {
      if (first) {
        x = e.offsetX;
        y = e.offsetY;
        first = false;
      }

      posx = e.pageX - x;
      posy = e.pageY - y;
      el.style.left = posx + 'px';
      el.style.top = posy + 'px';
    }
  }
});
.draggable {
  position: absolute;
  z-index: 1;
  top: 100px;
}
<section class="dragscroll">
  <div class="draggable">
    <textarea></textarea>
   </div>
</section>

<section class="dragscroll">
  <div class="draggable">
    <textarea></textarea>
  </div>
</section>
sample
  • 392
  • 2
  • 10