Commit 214d741b authored by Kushal Pandya's avatar Kushal Pandya

Add support for `offset` values in `isInViewport`

parent e2667b76
...@@ -118,12 +118,13 @@ export const handleLocationHash = () => { ...@@ -118,12 +118,13 @@ export const handleLocationHash = () => {
// Check if element scrolled into viewport from above or below // Check if element scrolled into viewport from above or below
// Courtesy http://stackoverflow.com/a/7557433/414749 // Courtesy http://stackoverflow.com/a/7557433/414749
export const isInViewport = el => { export const isInViewport = (el, offset = {}) => {
const rect = el.getBoundingClientRect(); const rect = el.getBoundingClientRect();
const { top, left } = offset;
return ( return (
rect.top >= 0 && rect.top >= (top || 0) &&
rect.left >= 0 && rect.left >= (left || 0) &&
rect.bottom <= window.innerHeight && rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth rect.right <= window.innerWidth
); );
......
...@@ -716,4 +716,29 @@ describe('common_utils', () => { ...@@ -716,4 +716,29 @@ describe('common_utils', () => {
expect(commonUtils.roundOffFloat(34567.14159, -5)).toBe(0); 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);
});
});
}); });
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment