Skip to content

Instantly share code, notes, and snippets.

@stripedpurple
Created January 13, 2023 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stripedpurple/1fc49a25bed0506a4d899763d56789db to your computer and use it in GitHub Desktop.
Save stripedpurple/1fc49a25bed0506a4d899763d56789db to your computer and use it in GitHub Desktop.
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