как перетягивать div мышкой

как сделать так чтобы красный div при удержании левой кнопки мыши работал так а не при mousemove

const cursor = document.querySelector('.cursor');

document.addEventListener( 'mousemove', e => {
  cursor.style.left = e.clientX + 'px';
  cursor.style.top = e.clientY + 'px';
});
.cursor {
  width: 30px;
  height: 30px;
  transform: translate(-50%,-50%);
  position: absolute;
  background-color: red;
}
<div class="cursor"></div>


Ответы (1 шт):

Автор решения: Алексей Шиманский

В грубом приближении так:

const cursor = document.querySelector('.cursor');
let canDrag = false;

document.addEventListener( 'mousemove', e => {
  if (!canDrag)
    return;
    
  cursor.style.left = e.clientX + 'px';
  cursor.style.top = e.clientY + 'px';
});

document.addEventListener( 'mouseup', e => canDrag = false);
cursor.addEventListener( 'mousedown', e => canDrag = true);
.cursor {
  width: 30px;
  height: 30px;
  transform: translate(-50%,-50%);
  position: absolute;
  background-color: red;
}
<div class="cursor"></div>

→ Ссылка