Permalink
Browse files

feat(dom utils): Add offset and position methods

  • Loading branch information...
tmorehouse committed Sep 15, 2017
1 parent 9d26697 commit baf15caaefd9e5f55df8e33f85b7bfde2810073d
Showing with 54 additions and 0 deletions.
  1. +54 −0 lib/utils/dom.js
@@ -126,6 +126,57 @@ dom.getBCR = function(el) {
return dom.isElement(el) ? el.getBoundingClientRect() : null;
};

// Get computed style object for an element
dom.getCS = function(el) {
return dom.isElement(el) ? window.getComputedStyle(el) : {};
};

// Return an element's offset wrt document element
// https://j11y.io/jquery/#v=git&fn=jQuery.fn.offset
dom.offset = function(el) {
if (dom.isElement(el)) {
const pos = { top: 0, left: 0 };
if (el.getClientRects().length) {
const bcr = dom.getBCR(el);
const win = el.ownerDocument.defaultView;
pos.top = bcr.top + win.pageYOffset;
pos.left = bcr.left + win.pageXOffset;
}
return pos;
}
};

// Return an element's offset wrt to it's offsetParent
// https://j11y.io/jquery/#v=git&fn=jQuery.fn.position
dom.position = function(el) {
if (!dom.isElement(el)) {
return;
}
let parentOffset = { top: 0, left: 0 };
let offset;
if (dom.getCS(el).position === 'fixed') {
offset = dom.getBCR(el);
} else {
offset = dom.offset(el);
const doc = el.ownerDocument;
const docElem = doc.documentElement;
let offsetParent = el.offsetParent || docElem;
while (offsetParent && (offsetParent === doc.body || offsetParent === docElem) &&
dom.getCS(offsetParent).position === 'static') {
offsetParent = offsetParent.parentNode;
}
if (offsetParent && offsetParent !== el && offsetParent.nodeType === Node.ELEMENT_TYPE) {
parentOffset = dom.offset(offsetParent);
parentOffset.top += parseFloat(dom.getCS(offsetParent).borderTopWidth);
parentOffset.left += parseFloat(dom.getCS(offsetParent).borderLeftWidth);
}
}
return {
top: offset.top - parentOffset.top - parseFloat(dom.getCS(el).marginTop),
left: offset.left - parentOffset.left - parseFloat(dom.getCS(el).marginLeft)
};
};

// Attach an event listener to an element
dom.eventOn = function(el, evtName, handler) {
if (el && el.addEventListener) {
@@ -155,6 +206,9 @@ export const setAttr = dom.setAttr;
export const removeAttr = dom.removeAttr;
export const getAttr = dom.getAttr;
export const getBCR = dom.getBCR;
export const getCS = dom.getCS;
export const offset = dom.offset;
export const position = dom.position;
export const eventOn = dom.eventOn;
export const eventOff = dom.eventOff;

0 comments on commit baf15ca

Please sign in to comment.