Skip to content

Instantly share code, notes, and snippets.

@yairEO
Created May 27, 2021 14:33
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 yairEO/69835f1321e1ecd567110df4d5bb20f3 to your computer and use it in GitHub Desktop.
Save yairEO/69835f1321e1ecd567110df4d5bb20f3 to your computer and use it in GitHub Desktop.
Positions a DOM element next to a certain position
/**
* positions a DOM element next to a certain position
* @param {HTMLElement} elm DOM element node
* @param {Object} pos x,y which should probably be within the viewport visible area
*/
export default (elm, pos) => {
const overflowOffset = 20;
const pageSize = {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
const elmSize = {
w: elm.clientWidth,
h: elm.clientHeight
}
const newPos = {
left: pos.x + elmSize.w > pageSize.w // overflows right
? pageSize.w - elmSize.w - overflowOffset
: pos.x - elmSize.w/2,
top: pos.y + elmSize.h > pageSize.h // overflows bottom
? pageSize.h - elmSize.h - overflowOffset
: pos.y
// pos.y < elmSize.h // overflows top
}
elm.style.left = newPos.left;
elm.style.top = newPos.top;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment