This application was developed to restrict input to 300 words within a contest entry.
A sub brand of AEO, 77kids, hosted a contest asking customers to write about their child. Given the large number of potential entries, a word limit was required.
Word Count Calculation: The 'wordCounter' function takes the value from the textarea, trims leading whitespaces, and uses a regular expression to split the string into an array of words. The total word count is then calculated, considering the user agent to handle specific cases.
Live Word Count Update: The 'liveCount' function is responsible for updating the UI with the current word count. It dynamically changes the color of the text based on whether the user has exceeded the word limit.
Word Limit Enforcement: The 'wordLimit' function checks if the current word count exceeds the specified limit. This can be used to prevent users from submitting content that goes beyond the defined constraint.
function wordCounter() { // Retrieve the value from the textarea var essay_val = essay.value; // Trim leading whitespaces var leftTrim = /^\s+/; var trimmed = essay_val.replace(leftTrim, ""); // Split the string into words using regex var splitString = trimmed.split(/\s+|[\w\d]$|[.?!"]$/); // Calculate the word count var wordCount = (navigator.userAgent.indexOf('MSIE') > 0 ) ? (splitString.length+1) : splitString.length; return wordCount; }
function liveCount(){ // Get the current word count var curCount = wordCounter(); // Update the UI with the word count wordCountOutput.style.color = "#333"; wordCountOutput.innerHTML = (curCount - 1) + " of " + maxWords + " words"; // Check if the user has exceeded the word limit if (curCount > maxWords + 1){ wordCountOutput.style.color = "red"; wordCountOutput.innerHTML = "You've gone over " + maxWords + " words by " + (curCount - (maxWords + 1)) + " word(s)."; } }
function wordLimit(){ // Check if the word count exceeds the limit if (wordCounter() > maxWords + 1){ return false; } else { return true; } }