Skip to content

Instantly share code, notes, and snippets.

@daun
Created April 12, 2024 09:12
Show Gist options
  • Save daun/c0f7de60e3a3eb58ef6af1961faca33a to your computer and use it in GitHub Desktop.
Save daun/c0f7de60e3a3eb58ef6af1961faca33a to your computer and use it in GitHub Desktop.
Move document focus starting point
function setFocusStartingPoint(element: HTMLElement) {
element.focus({ preventScroll: true });
// Exit here if the element was successfully focused
if (element.matches(':focus')) return;
// Not focussed? Probably not a link/button/input
// In this case, we insert a focussable child into the element, focus it, and remove it again
const focusElement = createInvisibleFocusElement();
element.prepend(focusElement);
focusElement.focus({ preventScroll: true });
focusElement.remove();
}
function createInvisibleFocusElement() {
const element = document.createElement('div');
element.setAttribute('tabindex', '-1');
element.style.position = 'absolute';
element.style.width = '1px';
element.style.height = '1px';
element.style.overflow = 'hidden';
element.style.clip = 'rect(1px, 1px, 1px, 1px)';
element.style.clipPath = 'inset(50%)';
element.style.outline = 'none';
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment