06. Announcing the Count


You've written 0 words and 0 characters.

HTML

1
2
3
4
<label class="label" for="text">Enter your text below.</label>
<textarea class="textarea" id="text"></textarea>

<p aria-live="polite">You've written <strong><span id="word-count">0</span> words</strong> and <strong><span id="character-count">0</span> characters</strong>.</p>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Changes to the content in #word-count and #character-count 
should be announced to screen reader users. Test this with an actual screen reader
to hear how the announcements are actually made. */

const textArea = document.querySelector('#text');
const countCharOutput = document.querySelector('#character-count');
const countWordOutput = document.querySelector('#word-count');

function counter() {
const wordsArr = textArea.value.split(/[\n\r\s]+/g).filter(item => {
return item.length > 0;
});
countCharOutput.textContent = textArea.value.length;
countWordOutput.textContent = wordsArr.length;
};

textArea.addEventListener('input', counter);