Skip to content

Keyboard focus location is lost when copying code or exiting search bar #2149

Open
@peterychang

Description

@peterychang

After activating the 'Copy to Clipboard' button via keyboard, the page focus resets. The same happens if the search overlay is escaped

This code fixes both issues, though the search bar will grab focus whenever the overlay is escaped; not sure if thats correct behavior or not.

document.addEventListener('DOMContentLoaded', function() {
  // Focus back onto copy button after copy event
  document.querySelectorAll('.copybtn').forEach(button => {
      button.addEventListener('click', async function(event) {
          // Save the current focus
          const focusedElement = document.activeElement;

          // Perform the copy action
          await copyToClipboard(this);

          // Restore the focus
          focusedElement.focus();
      });
  });

  // Focus back on search bar if overlay is escaped
  document.querySelectorAll('.search-button-field').forEach(button => {
    button.addEventListener('click', () => {
      // Save the element that had focus before opening the search
      const previousFocus = document.activeElement;

      document.addEventListener('keydown', (event) => {
        if (event.key === 'Escape') {
          // Restore focus to the previous element
          previousFocus.focus();
        }
      });
    });
  });
});

async function copyToClipboard(button) {
  const targetSelector = button.getAttribute('data-clipboard-target');
  const codeBlock = document.querySelector(targetSelector);
  try {
      await navigator.clipboard.writeText(codeBlock.textContent);
  } catch (err) {
      console.error('Failed to copy text: ', err);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs: discussionNeeds discussion before an implementation can be madetag: accessibilityIssues related to accessibility issues or efforts

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions