Skip to content

Commit 848c045

Browse files
authored
Fix position when body scrolled - PR#1 from glenn2223
Applied a fix so the position of the window doesn't affect the position of the anchor position data
2 parents 9ff9eb9 + 856d245 commit 848c045

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

src/index.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,13 @@ function position(options: IOptions): PositionData {
9898

9999
parent = parent.parentElement;
100100
}
101+
102+
// Finally, adjust for window scroll position
103+
const doc = document.documentElement;
104+
_anchorRect.y +=
105+
(window.scrollY || doc.scrollTop) - (doc.clientTop || 0);
106+
_anchorRect.x +=
107+
(window.scrollX || doc.scrollLeft) - (doc.clientLeft || 0);
101108
}
102109

103110
return {

tests/index.test.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,38 @@ describe('HoverPosition (collisions ignored)', () => {
6666
});
6767
});
6868
});
69+
70+
test('Window scroll adjusts output', () => {
71+
window.scrollX = 50;
72+
window.scrollY = 50;
73+
74+
const tP = 'top left',
75+
myA = 'top center',
76+
atA = 'bottom center';
77+
78+
helper.setupTest(tP);
79+
80+
const pData = position({
81+
...{ debug: true },
82+
...{
83+
my: myA,
84+
at: atA,
85+
target: document.querySelector<HTMLDivElement>(
86+
'.target',
87+
)!,
88+
anchor: document.querySelector<HTMLElement>('.anchor')!,
89+
collision: CollisionHandler.ignore,
90+
},
91+
}) as allData;
92+
93+
expect({
94+
left: parseInt(pData.left, 10),
95+
top: parseInt(pData.top, 10),
96+
}).toStrictEqual({
97+
left: helper.getLeft(tP, myA, atA) + 50,
98+
top: helper.getTop(tP, myA, atA) + 50,
99+
});
100+
101+
window.scrollX = 50;
102+
window.scrollY = 50;
103+
});

0 commit comments

Comments
 (0)