-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
50 lines (42 loc) · 1.26 KB
/
utils.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
function countWords(str) {
const words = str
.trim()
.split(/\s+/)
.filter((char) => char).length;
const allChars = str.match(/./gu);
const chars =
allChars &&
allChars.map((char) => char.trim()).filter((char) => char).length;
document.getElementById("words").innerText = `${words} words ${
chars ? chars : 0
} chars`;
}
function placeCaretAtEnd(element) {
element.focus();
if (
typeof window.getSelection != "undefined" &&
typeof document.createRange != "undefined"
) {
var range = document.createRange();
range.selectNodeContents(element);
range.collapse(false);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(element);
textRange.collapse(false);
textRange.select();
}
}
function isElement(element) {
return element instanceof Element || element instanceof HTMLDocument;
}
function selectElementContents(element) {
var range = document.createRange();
range.selectNodeContents(element);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}