-
-
Notifications
You must be signed in to change notification settings - Fork 322
Expand file tree
/
Copy pathchar_counter.js
More file actions
50 lines (41 loc) · 1.36 KB
/
char_counter.js
File metadata and controls
50 lines (41 loc) · 1.36 KB
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
/**
* Show the character counter below input fields and textareas
*/
import { translate } from "alchemy_admin/i18n"
class CharCounter extends HTMLElement {
connectedCallback() {
this.translation = translate("allowed_chars", this.maxChars)
this.formField = this.getFormField()
if (this.formField) {
this.createDisplayElement()
this.countCharacters()
this.formField.addEventListener("keyup", this)
}
}
disconnectedCallback() {
this.formField?.removeEventListener("keyup", this)
}
handleEvent(event) {
if (event.type === "keyup") this.countCharacters()
}
getFormField() {
const formFields = this.querySelectorAll("input, textarea")
return formFields.length > 0 ? formFields[0] : undefined
}
createDisplayElement() {
this.display = this.querySelector(":scope > .alchemy-char-counter")
if (this.display) return
this.display = document.createElement("small")
this.display.className = "alchemy-char-counter"
this.formField.after(this.display)
}
countCharacters() {
const charLength = this.formField.value.length
this.display.textContent = `${charLength} ${this.translation}`
this.display.classList.toggle("too-long", charLength > this.maxChars)
}
get maxChars() {
return this.getAttribute("max-chars") ?? 60
}
}
customElements.define("alchemy-char-counter", CharCounter)