Skip to content

Commit 045f2bc

Browse files
authored
Ensure page doesn't scroll down when pressing Escape to close the Dialog component (#3218)
* ensure we blur the `document.activeElement` when pressing `Escape` * update changelog
1 parent 300e9eb commit 045f2bc

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

packages/@headlessui-react/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
### Fixed
1111

1212
- [internal] Don’t set a focus fallback for Dialog’s in demo mode ([#3194](https://github.com/tailwindlabs/headlessui/pull/3194))
13+
- Ensure page doesn't scroll down when pressing `Escape` to close the `Dialog` component ([#3218](https://github.com/tailwindlabs/headlessui/pull/3218))
1314

1415
## [2.0.3] - 2024-05-07
1516

packages/@headlessui-react/src/components/dialog/dialog.tsx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,21 @@ function DialogFn<TTag extends ElementType = typeof DEFAULT_DIALOG_TAG>(
310310
if (event.key !== Keys.Escape) return
311311
event.preventDefault()
312312
event.stopPropagation()
313+
314+
// Ensure that we blur the current activeElement to prevent maintaining
315+
// focus and potentially scrolling the page to the end (because the Dialog
316+
// is rendered in a Portal at the end of the document.body and the browser
317+
// tries to keep the focused element in view)
318+
//
319+
// Typically only happens in Safari.
320+
if (
321+
document.activeElement &&
322+
'blur' in document.activeElement &&
323+
typeof document.activeElement.blur === 'function'
324+
) {
325+
document.activeElement.blur()
326+
}
327+
313328
close()
314329
})
315330

0 commit comments

Comments
 (0)