Add support for offset values in isInViewport

This commit is contained in:
Kushal Pandya 2019-01-08 18:37:21 +05:30
parent e2667b7654
commit 214d741ba5
2 changed files with 29 additions and 3 deletions

View file

@ -118,12 +118,13 @@ export const handleLocationHash = () => {
// Check if element scrolled into viewport from above or below
// Courtesy http://stackoverflow.com/a/7557433/414749
export const isInViewport = el => {
export const isInViewport = (el, offset = {}) => {
const rect = el.getBoundingClientRect();
const { top, left } = offset;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.top >= (top || 0) &&
rect.left >= (left || 0) &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
);

View file

@ -716,4 +716,29 @@ describe('common_utils', () => {
expect(commonUtils.roundOffFloat(34567.14159, -5)).toBe(0);
});
});
describe('isInViewport', () => {
let el;
beforeEach(() => {
el = document.createElement('div');
});
afterEach(() => {
document.body.removeChild(el);
});
it('returns true when provided `el` is in viewport', () => {
document.body.appendChild(el);
expect(commonUtils.isInViewport(el)).toBe(true);
});
it('returns false when provided `el` is not in viewport', () => {
el.setAttribute('style', 'position: absolute; top: -1000px; left: -1000px;');
document.body.appendChild(el);
expect(commonUtils.isInViewport(el)).toBe(false);
});
});
});