Search code examples
javascripthtmlcsscursorhide

How To hide cursor when dragging using JavaScript and css


I need to hide the cursor when dragging on the web browser. It's doesn't have to be an HTML element. If I click anywhere on the page and click and drag, the cursor should be hidden. When dragging finished cursor should be shown again. The cursor can't be hide when I click on the other buttons on the page. It should only be hidden when click and drag not when clicked. Is there any way I can achieve this using CSS and JavaScript? Thanks for your help.


Solution

  • The simplest solution is just use mousemove event

    var dragElement = null;
    document.addEventListener("mousemove", e =>
    {
      const isDragging = e.buttons == 1 && (e.movementX || e.movementY);
      document.body.classList.toggle("drag", isDragging);
      if (isDragging)
      {
        if (!dragElement)
          dragElement = e.target;
    
        console.log("dragging", dragElement);
      }
      else
      {
        dragElement = null;
      }
    });
    html, body
    {
      height: 100%;
      width: 100%;
    }
    body.drag
    {
      cursor: none;
      user-select: none;
    }
    
    #test
    {
      width: 10em;
      height: 10em;
      background-color: pink;
    }
    <div id="test">test</div>

    However this method will trigger "dragging" even if user clicked outside of the page. To solve this, we can track mousedown and mouseup events:

    var dragElement = null;
    document.addEventListener("mousedown", e =>
    {
      dragElement = e.target;
    });
    
    document.addEventListener("mouseup", e =>
    {
      dragElement = null;
    });
    
    document.addEventListener("mousemove", e =>
    {
      const isDragging = dragElement && (e.movementX || e.movementY);
      document.body.classList.toggle("drag", isDragging);
      if (isDragging)
      {
        console.log("dragging", dragElement);
      }
    });
    
    document.body.appendChild(document.createElement("canvas"));
    html, body
    {
      height: 100%;
      width: 100%;
    }
    body.drag
    {
      cursor: none;
      user-select: none;
    }
    
    #test
    {
      width: 30vw;
      height: 30vh;
      background-color: pink;
    }
    
    canvas
    {
      width: 30vw;
      height: 30vh;
      background-color: lightgreen;
    }
    <div id="test">test</div>