Skip to content

Commit

Permalink
fix: Fix getTargetScrollTop not working for body
Browse files Browse the repository at this point in the history
  • Loading branch information
guidobouman committed Apr 23, 2018
1 parent 80a0f96 commit 874efc1
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
22 changes: 13 additions & 9 deletions src/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,24 @@ export function getScrollingElement(container) {
return document.documentElement;
}

export function getTargetScrollTop(container, element) {
const elementTop = element.getBoundingClientRect().top;
const containerTop = container.getBoundingClientRect().top;
const scrollOffset = elementTop - containerTop;
return scrollOffset + container.scrollTop;
}

export function getElementsInContainerViewport(container, elementList) {
const containerRect = container === document.body ? {
function getContainerRect(container) {
return container === document.body ? {
top: 0,
left: 0,
bottom: window.innerHeight,
right: window.innerWidth,
} : container.getBoundingClientRect();
}

export function getTargetScrollTop(container, element) {
const containerRect = getContainerRect(container);
const elementRect = element.getBoundingClientRect();
const scrollOffset = elementRect.top - containerRect.top;
return scrollOffset + getScrollingElement(container).scrollTop;
}

export function getElementsInContainerViewport(container, elementList) {
const containerRect = getContainerRect(container);

return elementList.filter((element) => {
const elementRect = element.getBoundingClientRect();
Expand Down
20 changes: 20 additions & 0 deletions src/utilities.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,26 @@ describe('getTargetScrollTop', () => {
expect(getTargetScrollTop(...getElements(100, 0, 100))).toEqual(200);
expect(getTargetScrollTop(...getElements(100, 100, 100))).toEqual(100);
});

function getBodyElements(scrollTop, targetTop) {
const container = document.body;
getScrollingElement(document.body).scrollTop = scrollTop;

const target = document.createElement('div');
target.getBoundingClientRect = () => ({
top: targetTop,
});

return [container, target];
}

test('calculates scrollTop for target element in body', () => {
expect(getTargetScrollTop(...getBodyElements(0, 0))).toEqual(0);
expect(getTargetScrollTop(...getBodyElements(100, -100))).toEqual(0);
expect(getTargetScrollTop(...getBodyElements(100, 0))).toEqual(100);
expect(getTargetScrollTop(...getBodyElements(0, 100))).toEqual(100);
expect(getTargetScrollTop(...getBodyElements(100, 100))).toEqual(200);
});
});

describe('getElementsInContainerViewport', () => {
Expand Down

0 comments on commit 874efc1

Please sign in to comment.