-
Notifications
You must be signed in to change notification settings - Fork 0
/
unput.html
71 lines (66 loc) · 2.1 KB
/
unput.html
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html>
<h2>Controlled input</h2>
<textarea style="width: 100%" id="inputControlled"></textarea>
<h2>Native input</h2>
<textarea style="width: 100%" id="inputNative"></textarea>
<h2>Native readonly input</h2>
<textarea
style="width: 100%"
id="inputNativeReadonly"
readonly
value="readonly value"
></textarea>
<script>
const input = document.getElementById("inputControlled");
input.addEventListener("keydown", (e) => {
if (e.key === "ArrowRight" && e.shiftKey) {
input.setSelectionRange(input.selectionStart, input.selectionEnd + 1);
e.preventDefault();
} else if (e.key === "ArrowLeft" && e.shiftKey) {
input.setSelectionRange(input.selectionStart - 1, input.selectionEnd);
e.preventDefault();
} else if (e.key === "ArrowLeft" && (e.metaKey || e.ctrlKey)) {
let i = input.selectionStart;
while (i > 0) {
i--;
if (input.value.at(i) === " ") break;
}
input.setSelectionRange(i, i);
e.preventDefault();
} else if (e.key === "ArrowRight" && (e.metaKey || e.ctrlKey)) {
let i = input.selectionStart;
while (i < input.value.length - 1) {
i++;
if (input.value.at(i) === " ") break;
}
input.setSelectionRange(i, i);
e.preventDefault();
} else if (e.key === "ArrowRight" && !e.shiftKey) {
input.setSelectionRange(
input.selectionStart + 1,
input.selectionStart + 1
);
e.preventDefault();
} else if (e.key === "ArrowLeft" && !e.shiftKey) {
input.setSelectionRange(
input.selectionStart - 1,
input.selectionStart - 1
);
e.preventDefault();
} else if (
e.key !== "Meta" &&
e.key !== "Alt" &&
e.key !== "Shift" &&
e.key !== "Backspace" &&
e.key !== "Escape" &&
!e.metaKey &&
e.key !== "Control"
) {
input.value = input.value + e.key;
e.preventDefault();
}
console.log("keydown", input.selectionStart);
});
</script>
</html>