Skip to content

Instantly share code, notes, and snippets.

@patrickfox
Last active January 9, 2021 17:43
Show Gist options
  • Save patrickfox/ee5a0d093e0ab9f76441f8339ab4b8e1 to your computer and use it in GitHub Desktop.
Save patrickfox/ee5a0d093e0ab9f76441f8339ab4b8e1 to your computer and use it in GitHub Desktop.
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);
}
};
@patrickfox
Copy link
Author

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:

  • adds a tabindex="-1" to the target element
  • calls focus() on that element
  • adds a focusout listener that restores the original tabindex value (or removes it entirely) and removes the focusout listener

Usage

Params:

  • el - the target element
  • place_focus_before - (boolean, default: false) If true, will create a temporary element before the target element, place focus on that element, and delete that element on focusout

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment