Skip to content

Instantly share code, notes, and snippets.

@LemonNekoGH
Last active March 16, 2023 10:01
Show Gist options
  • Save LemonNekoGH/a8537950a2180713fee881be23968aac to your computer and use it in GitHub Desktop.
Save LemonNekoGH/a8537950a2180713fee881be23968aac to your computer and use it in GitHub Desktop.
A tool function use to hide cursor after specified time, show after move, and you can control this feature start and stop.
const useHideMouse = (time: number) => {
let timeoutId = -1
let lastElement
let lastElementCur = ""
const hideMouseAfter = (e: MouseEvent) => {
clearTimeout(timeoutId)
document.body.style.cursor = 'auto'
if (lastElement) {
lastElement.style.cursor = lastElementCur
}
lastElement = e.target
if (lastElement) {
lastElementCur = lastElement.style.cursor
}
timeoutId = setTimeout(() => {
lastElementCur = lastElement.style.cursor
if (lastElement)
lastElement.style.cursor = 'none'
document.body.style.cursor = 'none'
}, time)
}
return {
begin() {
document.addEventListener('mousemove', hideMouseAfter)
},
end() {
clearTimeout(timeoutId)
if (lastElement)
lastElement.style.cursor = lastElementCur
document.body.style.cursor = 'auto'
document.removeEventListener('mousemove', hideMouseAfter)
}
}
}
@LemonNekoGH
Copy link
Author

LemonNekoGH commented Mar 16, 2023

User guide

Copy this code to your code.
And remove parameter type in L1(No need to do this if using TypeScript):

- const useHideMouse = (time: number) => {
+ const useHideMouse = (time) => {

And L6(No need to do this if using TypeScript):

-   const hideMouseAfter = (e: MouseEvent) => {
+   const hideMouseAfter = (e) => {

Then use it:

const { begin, end } = useHideMouse(1000)
begin()

Now your cursor will hide after 1000ms when you stopped move your mouse, and will appear when you moving your mouse, you can stop this behaviour any time:

end()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment