UNPKG

vanillajs-browser-helpers

Version:

Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser

84 lines (83 loc) 3.08 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var isWindow_1 = __importDefault(require("./isWindow")); var isDOMElement_1 = __importDefault(require("./isDOMElement")); var isDocument_1 = __importDefault(require("./isDocument")); var scrollInfo_1 = __importDefault(require("./scrollInfo")); var size_1 = __importDefault(require("./size")); var getWindowPosition = function (win) { var top = win.screenLeft || win.screenX || 0; var left = win.screenY || win.screenTop || 0; var right = win.screen.availWidth - left - win.outerWidth; var bottom = win.screen.availHeight - top - win.outerHeight; return { top: top, left: left, right: right, bottom: bottom }; }; var getElementPosition = function (elm) { var rect = elm.getBoundingClientRect(); var vpScroll = scrollInfo_1.default(); var vpSize = size_1.default(); var elmSize = size_1.default(elm); var parentSize = size_1.default(elm.offsetParent || undefined); return { top: rect.top + vpScroll.y, left: rect.left + vpScroll.x, right: vpSize.width - rect.right - vpScroll.x, bottom: vpSize.height - rect.bottom - vpScroll.y, parent: { top: elm.offsetTop, left: elm.offsetLeft, right: parentSize.width - elm.offsetLeft - elmSize.width, bottom: parentSize.height - elm.offsetTop - elmSize.height }, viewport: { top: rect.top, left: rect.left, right: vpSize.width - rect.right, bottom: vpSize.height - rect.bottom } }; }; /** * Get the current position of a DOM element, either relative to the offsetParent * or relative to the document. If the element is the viewport or the window, the * position of the window is returned. * * @param elm - The DOM element to find the position of * @param relative = false - Find the position relative to the offsetParent rather than the document * @return the position information of the element * * @example * * ```ts * // Get the position of the current window * position(); * * // Get the position of the window of a given document * position(document); * position(document.documentElement); * position(document.body); * * // Get the position of a given element * position(someElement); * ``` */ function position(elm) { var currElm = elm; // Fallback to document if the element is one of the root elements if (isDOMElement_1.default(currElm, ['html', 'body'])) { currElm = currElm.ownerDocument; } // Fallback to window if the element is Document if (isDocument_1.default(currElm)) { currElm = currElm.defaultView; } // If we have no element, fall back to window currElm = currElm || window; return isWindow_1.default(currElm) ? getWindowPosition(currElm) : getElementPosition(currElm); } exports.default = position;