Last active
July 10, 2018 03:54
-
-
Save brookjordan/f94476eaa096da6ffe16af6ffa08b992 to your computer and use it in GitHub Desktop.
Create a list of tab-able elements sorted into tabbing order
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
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