Character Counter for Any Text Box With a Limit
Shows a live "120 / 500 characters" counter under every text box that has a maximum length, announced politely to screen readers as the limit gets close.
Opens WPIDE on
Code
(function () {
document.querySelectorAll('textarea[maxlength]').forEach(function (area) {
var max = parseInt(area.getAttribute('maxlength'), 10);
if (!max || max > 10000 || area.dataset.wpideCounter) {
return;
}
area.dataset.wpideCounter = '1';
var counter = document.createElement('p');
counter.className = 'wpide-char-counter';
counter.style.cssText = 'margin:.25em 0 0;font-size:.85em;opacity:.75;';
counter.setAttribute('aria-live', 'polite');
area.insertAdjacentElement('afterend', counter);
var update = function () {
var used = area.value.length;
counter.textContent = used + ' / ' + max + ' characters';
counter.style.opacity = used > max * 0.9 ? '1' : '.75';
counter.setAttribute('aria-live', used > max * 0.9 ? 'polite' : 'off');
};
area.addEventListener('input', update);
update();
});
})();
Notes
Works with any form that sets a maxlength of up to 10,000 characters on its textareas, including form plugins; very high technical limits (like the comment box's default) are ignored.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.