Last active
January 25, 2023 17:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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