Skip to content

Commit

Permalink
fix: incorrect focus setting when opening multiple terms sequentially
Browse files Browse the repository at this point in the history
  • Loading branch information
mournfulCoroner committed Dec 28, 2024
1 parent 0ed2bee commit cc50197
Showing 1 changed file with 8 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/js/term/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export function openDefinition(target: HTMLElement) {

definitionElement.classList.toggle(openClass);

trapFocus(definitionElement);
trapFocus(definitionElement, target);
}

export function closeDefinition(definition: HTMLElement) {
Expand Down Expand Up @@ -210,13 +210,19 @@ function getCoords(elem: HTMLElement) {
return {top: Math.round(top), left: Math.round(left)};
}

export function trapFocus(element: HTMLElement) {
export function trapFocus(element: HTMLElement, termButton: HTMLElement) {
const focusableElements = element.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])',
);
const firstFocusableElement = focusableElements[0] as HTMLElement;
const lastFocusableElement = focusableElements[focusableElements.length - 1] as HTMLElement;

// if another term was previously closed, the focus may still be on it
if (!firstFocusableElement && document.activeElement !== termButton) {
termButton.focus();
return;
}

if (firstFocusableElement) {
firstFocusableElement.focus();
}
Expand Down

0 comments on commit cc50197

Please sign in to comment.