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.
1 Answer
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>
3 Comments
Udara Sampath
It worked perfectly on the body of the page, but there is a little problem, I'm working with three js library and the canvas is autogenerated by the javascript, so it doesn't work when I click and drag on that canvas. Can you tell me how to do this for a canvas as well? I tried but not working
vanowm
It works fine with
canvas element that was added via javascript, as you can see in second example. So there must be something else in your code that changes cursor.Nicolas Stadler
doesnt work with elements that have the
draggable attribute
cursor: none;