Skip to content

Instantly share code, notes, and snippets.

@tobz-nz
Last active October 14, 2025 04:01
Show Gist options
  • Select an option

  • Save tobz-nz/3858e12b43aebc2c07585e7731c65672 to your computer and use it in GitHub Desktop.

Select an option

Save tobz-nz/3858e12b43aebc2c07585e7731c65672 to your computer and use it in GitHub Desktop.
A simple input character count custom element

Useage:

For forced limiting to the maxlength

<input id="my-input" maxlength="100">
<character-count for="my-input"></character-count>

or for just counting the characters - allows for negative count.

<input id="my-input">
<character-count for="my-input" maxlength="100"></character-count>
customElements.define('character-count', class extends HTMLElement {
#target = null;
connectedCallback() {
this.#target = document.getElementById(this.getAttribute('for'));
if (this.#target) {
this.#target.addEventListener('input', this);
this.value = this.#target.value;
}
}
disconnectedCallback() {
this.removeEventListener('input', this);
}
handleEvent(event) {
if (event.type === 'input') {
this.value = this.#target.value;
}
}
get maxlength() {
return this.getAttribute('maxlength') || this.#target.getAttribute('maxlength');
}
set value(value) {
this.textContent = this.maxlength - value.length;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment