javascript
27 lines · 7 steps
A live character counter for textareas
Attach an accessible, self-updating character count to any textarea and hand back a cleanup function.
Explained by
highlit
1function initCharacterCounter(textarea, options = {}) {
2 const maxLength = options.maxLength ?? 280;
3 const warnThreshold = options.warnThreshold ?? 0.9;
4
5 const counter = document.createElement('div');
6 counter.className = 'char-counter';
7 counter.setAttribute('aria-live', 'polite');
8 textarea.insertAdjacentElement('afterend', counter);
9
10 const update = () => {
11 const length = [...textarea.value].length;
12 const remaining = maxLength - length;
13
14 counter.textContent = `${remaining} character${remaining === 1 ? '' : 's'} remaining`;
15 counter.classList.toggle('char-counter--warning', length >= maxLength * warnThreshold);
16 counter.classList.toggle('char-counter--error', remaining < 0);
17 textarea.setAttribute('aria-invalid', String(remaining < 0));
18 };
19
20 textarea.addEventListener('input', update);
21 update();
22
23 return () => {
24 textarea.removeEventListener('input', update);
25 counter.remove();
26 };
27}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning a teardown function lets callers undo every side effect the setup created.
- 2aria-live and aria-invalid keep dynamic UI changes legible to screen readers.
- 3Spreading a string into an array counts Unicode code points rather than UTF-16 units.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
python
from typing import Any, Sequence, Mapping def render_markdown_table(
Rendering an aligned Markdown table in Python
string formatting
data transformation
closures
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-live-character-counter-for-textareas-explained-javascript-907c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.