Skip to content

Instantly share code, notes, and snippets.

@suguanYang
Created December 1, 2021 09:54
Show Gist options
  • Save suguanYang/fbc001222f0dc4cd52abd183cf75e8ad to your computer and use it in GitHub Desktop.
Save suguanYang/fbc001222f0dc4cd52abd183cf75e8ad to your computer and use it in GitHub Desktop.
tooltip with dynamic position
const { x: offsetLeft } = currentTarget.getBoundingClientRect();
const innerWidth = window.innerWidth;
const offsetRight = innerWidth - offsetLeft;
if (offsetLeft < TOOLTIP_WIDTH / 2) {
// if left space is too small
// --------
// |s. |
// |---- | s = offsetLeft
// | | left = -s = -
// --------
left = -offsetLeft + PAGE_PADDING;
} else if (offsetRight - PAGE_PADDING < TOOLTIP_WIDTH / 2) {
// if right space is too small
// --------
// | .s|
// | ----| s = (offsetRight)
// | | left = -(TOOLTIP_WIDTH - offsetRight) = ---
// --------
//
left = -(TOOLTIP_WIDTH - offsetRight) - PAGE_PADDING;
} else {
// normal case be center
// -------
// | . |
// | --- |
// | |
// -------
left = -TOOLTIP_WIDTH / 2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment