Skip to content

Instantly share code, notes, and snippets.

@erikvorhes
Last active January 25, 2023 17:43
Show Gist options
  • Save erikvorhes/2ceb77788b9db10c89fd7200440f2de8 to your computer and use it in GitHub Desktop.
Save erikvorhes/2ceb77788b9db10c89fd7200440f2de8 to your computer and use it in GitHub Desktop.
Ensures an ID matching the `window.location.hash` can and will receive focus if it isn't already focused.
/**
* Focuses an element even if it isn't focusable.
* @param {HTMLElement} target - element to focus
*/
function focusTarget(target) {
if (document.activeElement === target) {
return;
}
if (target.tabIndex < 0 && !target.getAttribute('tabIndex')) {
target.setAttribute('tabIndex', '-1');
}
target.focus();
}
function focusHash() {
const hash = window.location.hash;
const target = hash ? document.querySelector(hash) : null;
if (target) {
focusTarget(target);
}
}
window.addEventListener('DOMContentLoaded', focusHash);
window.addEventListener('hashchange', focusHash);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment