Home > Enterprise >  Change <textarea> font size when the value's length reaches a certain number
Change <textarea> font size when the value's length reaches a certain number

Time:06-22

As stated in the title, I want to change the textarea's font size after 50 or more values have been entered. For instance, my textarea's normal font size is 20px, but when I input something greater than or equal to 50 characters, the font size changes to 14px.

I tried doing

let textArea = document.getElementById("post");
var maxNumOfChars = 50;
const countCharacters = () => {
    let numOfEnteredChars = textArea.value.length;
};
textArea.addEventListener("inputs", countCharacters);
if(numOfEnteredChars >= 50) {
    textArea.style.fontSize = "1px";
}
<textarea name="post" placeholder="What's on you mind?" id="post"></textarea>

For sure, there's something wrong in my code (I'm a javascript beginner) so please correct my code or make a better way for doing it. Thanks

CodePudding user response:

First of all - event must be input, instead of inputs

The other thing - is the corrected business logic

const textArea = document.getElementById('post');

const resizeTextArea = () => {
    textArea.style.fontSize = textArea.value.length <= 50 ? '20px' : '14px';
};

textArea.addEventListener('input', resizeTextArea);
<textarea id="post"></textarea>

CodePudding user response:

Your countCharacters is a void function that doesn't return anything. And numOfEnteredChars variable inside the function is only accessible within that function's scope. You can't access to it outside the function.

let textArea = document.getElementById("post");

textArea.addEventListener('input', () => {
    textArea.value.length < 50 ? textArea.style.fontSize = '50px' : textArea.style.fontSize = '14px'
})

Worked for me!

  • Related