Skip to content

Instantly share code, notes, and snippets.

@huffmanks
Created February 18, 2022 18:32
Show Gist options
  • Save huffmanks/f93e1056a8dc3c1df35cac68a753c386 to your computer and use it in GitHub Desktop.
Save huffmanks/f93e1056a8dc3c1df35cac68a753c386 to your computer and use it in GitHub Desktop.
/*
* @title Character or word limit for textarea
* @desc Pick one and remove the other. Will not work together.
* @note Add maxlength attribute to textarea for character limit.
* @html <textarea id="message" maxlength="250"></textarea>
*/
window.addEventListener('DOMContentLoaded', () => { // For development environment testing
const wordMax = 250
const message = document.querySelector('#message')
// Create character limit element
const charsRemaining = document.createElement('div')
charsRemaining.innerText = 'Character limit: 250'
message.parentNode.insertBefore(charsRemaining, message)
// Create word limit element
const wordsRemaining = document.createElement('div')
wordsRemaining.innerText = `Word limit: ${wordMax}`
message.parentNode.insertBefore(wordsRemaining, message)
// Textarea onInput event
message.addEventListener('input', ({ target }) => {
// Update character limit text
let charsLeft = target.maxLength - target.textLength
charsRemaining.innerText = `Character limit: ${charsLeft}`
// Create an array of words
let words = target.value.match(/\S+/g)
let wordCount = words.length
let wordsLeft = wordMax - wordCount
// Remove extra words
if (wordsLeft <= 0) {
target.value = words.slice(0, wordMax).join(' ')
}
// Update word limit text
wordsRemaining.innerText = `Word limit: ${wordsLeft}`
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment