skip to Main Content

I have a problem with changing the cursor during object dragging. I’m trying to figure out how to properly change the cursor at the moment of dragging.

I have a React component.
I tried to implement cursor change like this, but it doesn’t work. With this implementation, the cursor doesn’t change during dragging (it stays as the default crossed circle).

function App() {
  const dragTarget = useRef(null);

  function dragStartHandler(e) {
    dragTarget.current.style.cursor = 'move';
  }

  function dragEndHandler() {
    dragTarget.current.style.cursor = 'auto';
  }

  return (
    <div
   
      draggable
      onDragStart={dragStartHandler}
      onDragEnd={dragEndHandler}
      id="dragTarget"
      className="draggable-element"
    >
      Drag me!
    </div>
  );
}

Please help me understand how to manipulate cursor styles correctly during dragging. Thank you in advance.

2

Answers


  1. Changing the cursor style is not supported by most browsers. I think the cursor style of the element being dragged is determined by the browser and cannot be overridden by CSS or JavaScript.

    A possible solution is to change the cursor style of the document body instead, which will affect the cursor style of the whole page. You can do this by adding the following lines to your code:

    function dragStartHandler(e) {
    document.body.style.cursor = 'move';
    }
    
    function dragEndHandler() {
    document.body.style.cursor = 'auto';
    }
    
    Login or Signup to reply.
  2. You can use :active to style this:

    div {
       cursor: grab;
    }
    
    div:active {
      cursor: grabbing;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search