Skip to content

Instantly share code, notes, and snippets.

@tyte
Last active April 15, 2022 10:57
Show Gist options
  • Save tyte/b134e14fbb8a6c51380d813bce0a857b to your computer and use it in GitHub Desktop.
Save tyte/b134e14fbb8a6c51380d813bce0a857b to your computer and use it in GitHub Desktop.
JS ARIA character and words count
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Character & Word Count</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
label {
display: block;
width: 100%;
}
textarea {
min-height: 24em;
width: 100%;
}
</style>
</head>
<body>
<h1 >Character & Word Count</h1>
<label for="text">Enter your text below.</label>
<textarea id="text"></textarea>
<p aria-live="polite" aria-atomic="true">You've written <strong><span id="word-count">0</span> words</strong> and <strong><span id="character-count">0</span> characters</strong>.</p>
<script>
// Get the elements
let text = document.querySelector('#text');
let charCount = document.querySelector('#character-count');
let wordCount = document.querySelector('#word-count');
// Listen for changes to the text area content
text.addEventListener('input', function () {
// Split regex: '/[\s]+/g'
// /regex/g specifies a global match https://www.w3schools.com/jsref/jsref_regexp_g.asp
let words = text.value.split(/[\s]+/g).filter(function (word) {
// Only count words with length
return word.length;
});
// Display the characters count
wordCount.textContent = words.length;
charCount.textContent = text.value.length;
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment