Open
Description
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);
}
}