Created
March 8, 2019 18:38
-
-
Save gugahoa/d1bd5037930973fcb9afbe20f432a540 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://usehooks.com/useOnClickOutside/ | |
export function useOnClickOutside(ref, handler) { | |
useEffect( | |
() => { | |
let touchendTimeout = null; | |
const listener = event => { | |
touchendTimeout = null; | |
// If user clicks inside the element, return | |
if (!ref.current || ref.current.contains(event.target)) { | |
return; | |
} | |
// If user clicks on scrollbar, return | |
if (document.documentElement.clientWidth <= event.clientX | |
|| document.documentElement.clientHeight <= event.clientY) { | |
return; | |
} | |
handler(event); | |
}; | |
const bouncedListener = (event) => { | |
touchendTimeout = setTimeout(() => listener(event), 500); | |
console.log('touchedTimeout', touchendTimeout); | |
}; | |
const cancelListenerTrigger = () => { | |
console.log('cancelListenerTrigger', touchendTimeout); | |
if (touchendTimeout !== null) { | |
clearTimeout(touchendTimeout) | |
} | |
}; | |
document.addEventListener('mousedown', listener); | |
document.addEventListener('touchstart', bouncedListener); | |
document.addEventListener('scroll', cancelListenerTrigger); | |
return () => { | |
document.removeEventListener('mousedown', listener); | |
document.removeEventListener('touchstart', bouncedListener); | |
document.removeEventListener('scroll', cancelListenerTrigger); | |
}; | |
}, | |
[ref, handler] | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment