Created
January 13, 2023 14:53
-
-
Save stripedpurple/1fc49a25bed0506a4d899763d56789db 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
import type { Directive } from "vue"; | |
const listOfFocusable = `a[href]:not([tabindex='-1']), | |
area[href]:not([tabindex='-1']), | |
input:not([disabled]):not([tabindex='-1']), | |
select:not([disabled]):not([tabindex='-1']), | |
textarea:not([disabled]):not([tabindex='-1']), | |
button:not([disabled]):not([tabindex='-1']), | |
iframe:not([tabindex='-1']), | |
[tabindex]:not([tabindex='-1']), | |
[contentEditable=true]:not([tabindex='-1'])` | |
const focusAtIndex = ($el: HTMLElement, idx = 0) => { | |
const focusable: NodeList = $el.querySelectorAll(listOfFocusable); | |
if (idx === -1) idx = focusable.length - 1; | |
console.log(idx); | |
focusable[idx]?.focus(); | |
}; | |
const focus = (el: HTMLElement, { value, arg }) => { | |
value = +value; | |
if (isNaN(value) && arg === "at") return; | |
switch (arg) { | |
case "first": | |
focusAtIndex(el, 0); | |
break; | |
case "last": | |
focusAtIndex(el, -1); | |
break; | |
case "at": | |
focusAtIndex(el, value); | |
break; | |
default: | |
el.focus(); | |
} | |
}; | |
export default { | |
mounted: focus, | |
} as Directive<any, any>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment