Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Last active July 10, 2018 03:54
Show Gist options
  • Save brookjordan/f94476eaa096da6ffe16af6ffa08b992 to your computer and use it in GitHub Desktop.
Save brookjordan/f94476eaa096da6ffe16af6ffa08b992 to your computer and use it in GitHub Desktop.
Create a list of tab-able elements sorted into tabbing order
function tabMap(within = document.documentElement) {
let TABBABLE_SELECTOR = [
'area',
'button',
'select',
'textarea',
'summary',
'details',
'[tabindex]',
'a[href]',
//'link[href]',
'svg a[xlink\\:href]',
'input:not([type="hidden"]):not([hidden]):not([disabled])',
]
.map(str => `${str}:not([tabindex*="-"])`)
.concat([
'video[controls]',
'audio[controls]',
])
.join();
let TABBABLE_ELEMENTS = [...within.querySelectorAll(TABBABLE_SELECTOR)];
return TABBABLE_ELEMENTS.slice(0).sort((a, b) => {
let tabindexA = a.attributes.tabindex && +a.attributes.tabindex.value;
let tabindexB = b.attributes.tabindex && +b.attributes.tabindex.value;
if (!isNaN(tabindexA) && !isNaN(tabindexB)) {
return tabindexA - tabindexB;
}
if (isNaN(tabindexA) && isNaN(tabindexB)) {
return positionDiff();
}
if (!isNaN(tabindexA) && tabindexA) {
return 1;
}
if (!isNaN(tabindexB) && tabindexB) {
return -1;
}
return positionDiff();
function positionDiff() {
return TABBABLE_ELEMENTS.indexOf(a) - TABBABLE_ELEMENTS.indexOf(b);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment