Last active
January 9, 2021 17:43
-
-
Save patrickfox/ee5a0d093e0ab9f76441f8339ab4b8e1 to your computer and use it in GitHub Desktop.
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
var access = function(el, place_focus_before) { | |
var focus_el, focus_method, ogti, onblur_el, onblur_temp_el, temp_el; | |
onblur_el = function(e) { | |
if (el.getAttribute('data-ogti')) { | |
el.setAttribute('tabindex', ogti); | |
} else { | |
el.removeAttribute('tabindex'); | |
} | |
el.removeAttribute('data-ogti'); | |
el.removeEventListener('focusout', focus_method); | |
}; | |
onblur_temp_el = function(e) { | |
temp_el.removeEventListener('focusout', focus_method); | |
temp_el.parentNode.removeChild(temp_el); | |
}; | |
focus_el = function(the_el) { | |
the_el.setAttribute('tabindex', '-1'); | |
the_el.addEventListener('focusout', focus_method); | |
the_el.focus(); | |
}; | |
focus_method = onblur_el; | |
if (place_focus_before) { | |
temp_el = document.createElement('span'); | |
if (typeof place_focus_before === 'string') { | |
temp_el.innerHTML = place_focus_before; | |
} | |
temp_el.setAttribute('style', 'position: absolute;height: 1px;width: 1px;margin: -1px;padding: 0;overflow: hidden;clip: rect(0 0 0 0);border: 0;'); | |
temp_el = el.parentNode.insertBefore(temp_el, el); | |
focus_method = onblur_temp_el; | |
focus_el(temp_el); | |
} else { | |
ogti = el.getAttribute('tabindex'); | |
if (ogti) { | |
el.setAttribute('data-ogti', ogti); | |
} | |
focus_el(el); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
access.js
Overview
access.js is a standalone, vanilla JavaScript utility that allows developers to temporarily place focus on any element in the page. To place focus on an element, it must be able to accept focus. Natively interactive elements - like form elements, links, buttons - can receive focus, but for the purposes of accessibility, there is a common requirement to move focus based on an appropriate user action, like clicking an in-page link.
How It Works
This script works as follows:
tabindex="-1"
to the target elementfocus()
on that elementfocusout
listener that restores the original tabindex value (or removes it entirely) and removes the focusout listenerUsage
Params: