Code examples

Use semantic HTML

This semantic HTML contains all accessibility features by default.

  • Delay the update for dynamic counters
    • Use setTimeoutto allow the accessibility tree and screen reader time to update in a logical fashion
  • Do not reference the role="status" element with aria-describedby
    • This causes a bug in VoiceOver
const textarea = document.getElementById('message');
if(textarea) {
    const chars = document.getElementById('currentChars');
    textarea.addEventListener("input", event => {
        const target = event.currentTarget;
        const maxLength = target.getAttribute("maxlength");
        const currentLength = target.value.length;
        setTimeout(function() {
            chars.innerHTML = maxLength - currentLength;
        }, 10);
    });
}
<label for="message">
  Your message
</label>
<textarea 
  id="message"
  maxlength="50"
  aria-describedby="charcounter">
</textarea>
<div role="status">
  <!-- Do not reference the status element with aria-describedby 
       Doing so will not work in VoiceOver -->
  <div id="charcounter" class="hint">
    <span id="currentChars">50</span> 
    of 50
    <span class="hidden">
      characters remaining
    </span>
  </div>
</div>
50 of 50

Related textarea multiline input entries