Skip to content

Commit 3c2b217

Browse files
committed
fix: Prevent scroll event listener while handling focusOn
1 parent 54d6915 commit 3c2b217

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

src/@types/index.d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export interface IFocusOnScrollProps {
1313

1414
export interface IFocusOnScrollState {
1515
focusIndex: string;
16+
focusOnTriggered: boolean;
1617
}
1718

1819
export type ChildrenArray = any[];

src/components/FocusOnScroll.tsx

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,11 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
2525
super(props);
2626
this.state = {
2727
focusIndex: getFocusIndex(this.props.focusOn),
28+
/** focusOnTriggered: This field prevents scroll event listener to execute
29+
* when user specified focused index. It means in focusOnHandler
30+
* when we call window.scrollY() function it prevents triggering scroll event
31+
**/
32+
focusOnTriggered: false,
2833
};
2934
}
3035
private debounceResizeHandler = () => debounce(this.scrollHandler, DELAY_TIME_IN_MS);
@@ -63,9 +68,21 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
6368
return;
6469
}
6570
const { height } = focusElement.getBoundingClientRect();
66-
const scrollPosition = (focusElement.offsetTop + (height / 2)) - (window.innerHeight / 2);
67-
window.scrollTo(0, scrollPosition - 1);
68-
this.setFocusIndex(focusIndex);
71+
const scrollPosition = Math.max((focusElement.offsetTop + (height / 2)) - (window.innerHeight / 2), 1);
72+
73+
this.setState({
74+
focusOnTriggered: true,
75+
}, () => {
76+
window.scrollTo({
77+
top: scrollPosition - 1,
78+
left: 0,
79+
behavior: 'smooth',
80+
});
81+
this.setFocusIndex(focusIndex);
82+
setTimeout(() => {
83+
this.setState({ focusOnTriggered: false });
84+
}, DELAY_TIME_IN_MS);
85+
});
6986
}
7087

7188
/**
@@ -91,6 +108,9 @@ class FocusOnScroll extends React.Component<IFocusOnScrollProps, IFocusOnScrollS
91108
}
92109

93110
public scrollHandler = (): void => {
111+
if (this.state.focusOnTriggered) {
112+
return;
113+
}
94114
const focusIndex = findFocusElement();
95115
if (focusIndex) {
96116
this.setFocusIndex(focusIndex);

0 commit comments

Comments
 (0)