Last active
February 5, 2022 16:22
-
-
Save thezacharytaylor/7667be6bd85eeb36ff6a2e499cc2304c to your computer and use it in GitHub Desktop.
a11y Tooltip Vertical Bounding w/ reworked check function
This file contains 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
// Rest of code can be found on: | |
// https://codepen.io/Moiety/pen/LaPvWy | |
// | |
// Reworked Check function | |
checkBoundingBox() { | |
let bounds = this.tooltip.getBoundingClientRect() | |
this.moveTooltipHorizontally(bounds) | |
this.moveTooltipVertically(bounds) | |
} | |
// New horizontal check function | |
moveTooltipHorizontally(bounds) { | |
let windowWidth = window.innerWidth | |
if (bounds.right > windowWidth) { | |
this.moveTooltipLeft(bounds, windowWidth) | |
} else if (bounds.left < 0 ) { | |
this.moveTooltipRight(bounds) | |
} | |
} | |
// Enables vertical bounding checks w/ a combined top & bottom margin of 32 | |
moveTooltipVertically(bounds) { | |
// Assuming a flat 16x16 top to bottom margin with the 32. | |
let windowHeight = window.innerHeight | |
let combinedHeight = bounds.height + this.container.getBoundingClientRect().height + 32 | |
if (bounds.bottom > (windowHeight - Math.ceil(combinedHeight))) { | |
this.container.classList.add('top') | |
} else if (bounds.bottom < windowHeight) { | |
this.container.classList.remove('top') | |
} | |
} | |
// ========================================= | |
// Optional moveTooltipVertically function: | |
// ========================================= | |
// Function that finds the margin dynamically | |
moveTooltipUpDown(bounds) { | |
let windowHeight = window.innerHeight | |
let styles = window.getComputedStyle(this.tooltip); | |
let topMargin = styles.getPropertyValue('margin-top').match(/\d+/) | |
let bottomMargin = styles.getPropertyValue('margin-bottom').match(/\d+/) | |
let combinedHeight = bounds.height + this.container.getBoundingClientRect().height + parseInt(topMargin) + parseInt(bottomMargin) | |
if (bounds.bottom > (windowHeight - Math.ceil(combinedHeight))) { | |
this.container.classList.add('top') | |
} else if (bounds.bottom < windowHeight) { | |
this.container.classList.remove('top') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment