Skip to content

Instantly share code, notes, and snippets.

@ricealexander
Created August 10, 2020 20:59
Show Gist options
  • Save ricealexander/5bfabc09d51b903461292ca58d72547e to your computer and use it in GitHub Desktop.
Save ricealexander/5bfabc09d51b903461292ca58d72547e to your computer and use it in GitHub Desktop.
Detect hovering with JavaScript
function onHover (element, hoverOnCallback, hoverOffCallback = function () {}) {
let hoverInterval
function hoverOn () {
hoverInterval = setInterval(hoverOnCallback, 100)
}
function hoverOff () {
if (hoverInterval) clearInterval(hoverInterval)
hoverOffCallback()
}
element.addEventListener('mouseover', hoverOn)
element.addEventListener('mouseout', hoverOff)
// Remove hover if user hovers over something else
// There is a bug where if the user's cursor leaves the browser without a
// mouse gesture, mouseout never fires. Such circumstances include:
// • User changes windows with Alt+Tab
// • User right-clicks an element and then clicks outside their browser
// • User attempts to drag the element outside of browser
// • Another application forces their window to be focused
window.addEventListener('mousemove', event => {
const { target } = event
const isHovering = element.contains(target)
if (!isHovering) hoverOff()
})
}
// Note: All of this functionality can probably be combined within a single
// window mousemove event. Consider refactoring.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment