Skip to content

Instantly share code, notes, and snippets.

@willmorgan
Created June 23, 2015 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willmorgan/d62f7ada85e9b4973684 to your computer and use it in GitHub Desktop.
Save willmorgan/d62f7ada85e9b4973684 to your computer and use it in GitHub Desktop.
"Anchor" an element around another element.
function getAnchorCoordinates(anchor, container, me) {
me = me || this.el;
container = container || document.body;
// Margins - use half a margin for normal positioning, the full margin for compensating
// against the container box
var offsetMarginX = 30;
var offsetMarginY = 30;
// The coordinates we're anchoring around
var anchorBox = anchor.getBoundingClientRect();
// The container to ensure this element doesn't fall out of
var containerBox = container.getBoundingClientRect();
// The coordinates of the currently rendered element
var ownBox = me.getBoundingClientRect();
// Ideal positioning: centred horizontally beneath the anchor, with some margin.
var ownLeft = anchorBox.left + anchorBox.width / 2 - ownBox.width / 2;
var ownTop = anchorBox.bottom + offsetMarginY / 2;
// If the first attempt means the bottom of the box falls out, compensate:
if(ownTop + ownBox.height > containerBox.bottom) {
// Try and position the element above the anchor with the same margin
ownTop = anchorBox.top - ownBox.height - offsetMarginY / 2;
}
// If we're now rendering too far "above" the container, bring it back down.
if(ownTop < containerBox.top) {
ownTop = containerBox.top + offsetMarginY / 2;
}
// The same for the left...
if(ownLeft + ownBox.width > containerBox.right) {
ownLeft = containerBox.right - ownBox.width - offsetMarginX;
}
// If too far to the left, push right.
if(ownLeft < containerBox.left) {
ownLeft = containerBox.left + offsetMarginX;
}
return {
top: ownTop,
left: ownLeft
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment