I've been working on creating a popup box that displays text positioned away from an element when the cursor hovers over it. Check out a simplified demo here.
Currently, the popup box collapses when it gets close to the bounding box. I'd like it to appear at the bottom-left (if it overflows to the right) or top-left (if it overflows to the bottom and right) of the hovered element's position if it exceeds the boundaries.
The text and position displayed are dynamically generated, meaning I won't know them in advance.
My current solution involves using Javascript:
- Retrieve the text to be displayed. Calculate the width of the text by multiplying the number of characters by 0.25em.
- Determine the total width of the displayed text + padding (left and right), referred to as
textLength
. This sets the popup's width to ensure all text fits on one line. - If the cursor's x position +
textLength
is greater than the box width, shift the position of the popup box to the left by subtractingtextLength
and some distance from the element. - Repeat the same check for the y position. If the cursor position + line height (1em) + bottom padding exceeds the box height, adjust the y position accordingly.
This solution works, but I'm interested in exploring more efficient alternatives that don't involve character counting. Is there a more elegant way to achieve this, perhaps using CSS only without Javascript?