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
49 lines (48 loc) • 1.75 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const isDOMChildNode_1 = __importDefault(require("./isDOMChildNode"));
const hidden_1 = __importDefault(require("./hidden"));
/**
* Determines whether the element is in the area of the viewport or not.
*
* @param elm - DOM element to test
* @param threshold - The distance to the edge of the viewport before
* the element is no longer inside in the viewport area,
* in pixels
*
* @return An object with indications of where the element is compared to the viewport area
*
* @example
*
* ```ts
* // Element inside viewport
* const { inside } = inView(myElement);
* // -> inside === true
*
* // Element outside viewport
* const { inside, below } = inView(myElement);
* // -> inside === false; below === true
*
* // With a threshold
* const { inside } = inView(myElement, 30);
* // -> inside === true
* ```
*/
function inView(elm, threshold = 0) {
if (!isDOMChildNode_1.default(elm) || hidden_1.default(elm)) {
return { above: false, below: false, left: false, right: false, inside: false };
}
const rect = elm.getBoundingClientRect();
const vpWidth = window.innerWidth;
const vpHeight = window.innerHeight;
const above = rect.bottom - threshold <= 0;
const below = rect.top - vpHeight + threshold >= 0;
const left = rect.right - threshold <= 0;
const right = rect.left - vpWidth + threshold >= 0;
const inside = !above && !below && !left && !right;
return { above, below, left, right, inside };
}
exports.default = inView;