Created
January 24, 2024 02:14
-
-
Save tibotiber/627f71363db142ea9176076305cd33e2 to your computer and use it in GitHub Desktop.
Smart position of tooltips so it adapts to the position on screen
This file contains hidden or 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
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