-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
55 lines (42 loc) · 1.32 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(function () {
'use strict';
const keys = {
escape: 27,
};
let index = 0;
let isValidInput = (element) => {
while (element) {
let nodeName = element.nodeName.toLowerCase();
if (nodeName === 'body' || nodeName.includes('document')) return true;
let rect = element.getBoundingClientRect();
if (rect.height == 0 || rect.width == 0) return false;
element = element.parentNode;
}
return true;
};
const inputSelector =
"input[type='input'],input[type='search'],input[type='text'],input[type='tel'],input[type='email'],input[type='password'],[contenteditable],textarea";
function focusInput(e) {
e.preventDefault();
e.stopPropagation();
let allInputs = [...document.querySelectorAll(inputSelector)];
let validInputs = allInputs.filter((el) => isValidInput(el));
if (validInputs?.length === 0) {
validInputs = allInputs;
}
if (!validInputs) return;
if (index > validInputs.length - 1) {
index = validInputs.length - 1;
}
let input = validInputs[index];
if (e.keyCode === keys.escape) {
if (input) {
input.focus();
input.setSelectionRange(0, input.value.length);
index++;
if (index >= validInputs.length) index = 0;
}
}
}
document.addEventListener('keyup', focusInput);
})();