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

Improve focus management #56

Merged
merged 1 commit into from
Mar 1, 2024
Merged

Improve focus management #56

merged 1 commit into from
Mar 1, 2024

Conversation

imacrayon
Copy link
Owner

@imacrayon imacrayon commented Feb 13, 2024

The problem

I'm not totally satisfied with using x-focus for focus management, it falls short in some cases:

  • It sets focus after every request regardless of the response status: A UI might need to focus on one element after a successful request and a totally different element when there's an error.
  • Focusing elements via their ID doesn’t always work: When a new element is created through an AJAX request it may be impossible to assume what its ID will be.
  • It ignores autofocus: Alpine AJAX should respect this attribute since it's already browser-native.

It's worth noting that Alpine has a first party Focus plugin, it would be nice to have better support for those utilities.

x-autofocus to the rescue

This PR introduces a new x-autofocus attribute and deprecates x-focus. After an AJAX request is issued and content is merged on the page, the first element with the attribute x-autofocus, will be automatically focused. The same is true for the browser-standard autofocus attribute. The only difference between x-autofocus and autofocus is that x-autofocus does not trigger focus on initial page loads, only when AJAX content loads.

If multiple elements are targeted in an AJAX request each target is checked for an x-autofocus attribute in the order specified by x-target, so the first target containing an x-autofocus will receive focus.

Fixes #52

@imacrayon imacrayon marked this pull request as ready for review March 1, 2024 20:22
@imacrayon imacrayon merged commit b893380 into main Mar 1, 2024
1 check passed
imacrayon added a commit that referenced this pull request Mar 2, 2024
@imacrayon imacrayon deleted the focus branch March 2, 2024 02:30
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.

Add support for autofocus
1 participant