Sobes.tech
Middle

Task: drag with the mouse Make it possible to hold down the mouse button over a colored box and drag it while the button is held.

sobes.tech AI

Answer from AI

To implement dragging a colored box with a mouse, you can use the mousedown, mousemove, and mouseup events in JavaScript. When the mouse button is pressed on the box, record the initial cursor coordinates and the element's position, then update the box's position as the mouse moves until the button is released.

Example implementation in plain JS:

<div id="box" style="width:100px; height:100px; background-color:tomato; position:absolute; top:100px; left:100px; cursor:pointer;"></div>

<script>
  const box = document.getElementById('box');
  let isDragging = false;
  let startX, startY, origX, origY;

  box.addEventListener('mousedown', (e) => {
    isDragging = true;
    startX = e.clientX;
    startY = e.clientY;
    const rect = box.getBoundingClientRect();
    origX = rect.left;
    origY = rect.top;
    e.preventDefault();
  });

  document.addEventListener('mousemove', (e) => {
    if (!isDragging) return;
    const dx = e.clientX - startX;
    const dy = e.clientY - startY;
    box.style.left = origX + dx + 'px';
    box.style.top = origY + dy + 'px';
  });

  document.addEventListener('mouseup', () => {
    isDragging = false;
  });
</script>

This approach allows you to click and hold the mouse on the box and drag it around the screen while the mouse button is held down.

Task: drag with the mouse Make it possible to hold… - sobes.tech