Skip to content

Commit 5d83432

Browse files
jclijmansJos Clijmans
andauthored
fix : scrollIntoView does not work in shadow dom (#1168)
Co-authored-by: Jos Clijmans <[email protected]>
1 parent 25dcca6 commit 5d83432

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/index.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,23 @@ let getOptions = (options: any): StandardBehaviorOptions => {
7171
return { block: 'start', inline: 'nearest' }
7272
}
7373

74+
// Determine if the element is part of the document (including shadow dom)
75+
// Derived from code of Andy Desmarais
76+
// https://terodox.tech/how-to-tell-if-an-element-is-in-the-dom-including-the-shadow-dom/
77+
const isInDocument = (element: Node) => {
78+
var currentElement = element;
79+
while(currentElement && currentElement.parentNode) {
80+
if(currentElement.parentNode === document) {
81+
return true;
82+
} else if(currentElement.parentNode instanceof ShadowRoot) {
83+
currentElement = (currentElement.parentNode as ShadowRoot).host;
84+
} else {
85+
currentElement = currentElement.parentNode;
86+
}
87+
}
88+
return false;
89+
}
90+
7491
/**
7592
* Scrolls the given element into view, with options for when, and how.
7693
* Supports the same `options` as [`Element.prototype.scrollIntoView`](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) with additions such as `scrollMode`, `behavior: Function` and `skipOverflowHiddenElements`.
@@ -108,7 +125,7 @@ function scrollIntoView<T = unknown>(
108125
// Browsers treats targets that aren't in the dom as a no-op and so should we
109126
if (
110127
!target.isConnected ||
111-
!target.ownerDocument!.documentElement!.contains(target)
128+
!isInDocument(target)
112129
) {
113130
return
114131
}

0 commit comments

Comments
 (0)