Skip to content

Instantly share code, notes, and snippets.

@tibotiber
Created January 24, 2024 02:14
Show Gist options
  • Save tibotiber/627f71363db142ea9176076305cd33e2 to your computer and use it in GitHub Desktop.
Save tibotiber/627f71363db142ea9176076305cd33e2 to your computer and use it in GitHub Desktop.
Smart position of tooltips so it adapts to the position on screen
const viewerElement = document.getElementById('test') as HTMLElement
const tooltipInLeftHalfOfViewer = hoverState.tooltipPosition.screenX < viewerElement.clientWidth / 2
const tooltipInTopThirdOfViewer = hoverState.tooltipPosition.screenY < viewerElement.clientHeight / 3
const tooltipInBottomThirdOfViewer = hoverState.tooltipPosition.screenY > (2 * viewerElement.clientHeight) / 3
tooltipElement?.style.setProperty('display', 'block')
tooltipElement?.style.setProperty('top', `${hoverState.tooltipPosition.screenY}px`)
let tX: string, tY: string
if (tooltipInLeftHalfOfViewer) {
tooltipElement?.style.setProperty('left', `${hoverState.tooltipPosition.screenX}px`)
tooltipElement?.style.setProperty('right', 'unset')
tX = '16px'
} else {
tooltipElement?.style.setProperty(
'right',
`${viewerElement.clientWidth - hoverState.tooltipPosition.screenX}px`
)
tooltipElement?.style.setProperty('left', 'unset')
tX = '-16px'
}
if (tooltipInBottomThirdOfViewer) {
tY = '-100%'
} else if (!tooltipInTopThirdOfViewer) {
tY = '-50%'
} else {
tY = '0'
}
tooltipElement?.style.setProperty('transform', `translate(${tX}, ${tY})`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment