Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure page doesn't scroll down when pressing Escape to close the Dialog component #3218

Merged
merged 2 commits into from
May 21, 2024

Conversation

RobinMalfait
Copy link
Member

This PR ensures that the page doesn't scroll down when pressing Escape to close an open Dialog component.

This only happens in Safari, and if the document.activeElement is an <input> for example. It also only happens when pressing Escape, not when clicking outside of the Dialog component.

The reason why is a bit confusing but it does make sense:

Whenever the the currently focused element is moved on the page, Safari will try to keep the document.activeElement in view. This means that when you press Escape that the <input> element is still focused, but since the Dialog closes, the <input> is still rendered in a portal at the end of the page. Because it's rendered there, Safari will try and keep it in view, which causes the page to scroll down.

It doesn't happen when clicking outside of the Dialog component because the document.activeElement will be the newly focused element, which is typically the <body> element.

To solve this, we will always call document.activeElement.blur() (which is also implicitly done when clicking outside of the Dialog component) when we press Escape.

Now, the <input> element is no longer focused, and Safari won't try to keep it in view, which prevents the page from scrolling down.

Copy link

vercel bot commented May 20, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
headlessui-react ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 20, 2024 2:20pm
headlessui-vue ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 20, 2024 2:20pm

Copy link
Member

@adamwathan adamwathan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice fix!

@RobinMalfait RobinMalfait merged commit 045f2bc into main May 21, 2024
8 checks passed
@RobinMalfait RobinMalfait deleted the fix/demo-mode-dialog branch May 21, 2024 11:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants