Move Button Left and Right with Mouse When Clicked

63 Views Asked by At

When I hold the button with the class btnn and move the mouse cursor left and right, I want the button to move (left and right), and stop moving when I release mouse cursor.

<div class="box1 d-flex flex-column justify-content-between h-100">
  <div class="target d-flex gap-3">
    <div class="block1">
      <div class="square1"></div>
      <div class="square1"></div>
      <div class="square1"></div>
    </div>
    <div class="block1">
      <div class="square1"></div>
      <div class="square1"></div>
      <div class="square1"></div>
      <div class="square1"></div>
      <div class="square1"></div>
    </div>
    <div class="block1">
      <div class="square1"></div>
      <div class="square1"></div>
      <div class="square1"></div>
    </div>
  </div>
  <div class="Targeter">
    <div class="btnn"></div>
  </div>
</div>
1

There are 1 best solutions below

0
Rahul Panchal On
    const moveButton = document.getElementById('moveButton');
let isMouseDown = false;

moveButton.addEventListener('mousedown', () => {
    isMouseDown = true;
    moveButton.style.cursor = 'grabbing';
});

document.addEventListener('mouseup', () => {
    isMouseDown = false;
    moveButton.style.cursor = 'grab';
});

document.addEventListener('mousemove', (event) => {
    if (isMouseDown) {
        moveButton.style.left = `${event.clientX - moveButton.clientWidth / 2}px`;
        moveButton.style.top = `${event.clientY - moveButton.clientHeight / 2}px`;
    }
});