Skip to content

Instantly share code, notes, and snippets.

@aimahdi
Created February 8, 2025 17:07
Show Gist options
  • Save aimahdi/b1405825a02099583afb59cfe431f250 to your computer and use it in GitHub Desktop.
Save aimahdi/b1405825a02099583afb59cfe431f250 to your computer and use it in GitHub Desktop.
window.onload = function() {
// Only 10 characters can be added. Change this value to apply more characters.
let textAreaCharsLimit = 10;
//find the specific text area field using the classname
let textAreaField = document.querySelector('.haslimit');
// Create a new div to display the remaining characters
let newDiv = document.createElement("div");
// Add a class to style it later
newDiv.classList.add("showlimit");
newDiv.textContent = textAreaCharsLimit + " characters remaining";
textAreaField.parentNode.insertBefore(newDiv, textAreaField.nextSibling);
// Add an input event listener to the text area
textAreaField.oninput = function (event) {
let remainingChars = textAreaCharsLimit - event.target.value.length;
if (remainingChars < 0) {
event.preventDefault();
event.target.value = event.target.value.slice(0, textAreaCharsLimit); // Truncate the text
newDiv.textContent = "You have crossed the maximum limit";
newDiv.style.color = "red";
} else {
newDiv.textContent = remainingChars + " characters remaining";
newDiv.style.color = "black";
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment