Reputation: 204
How can I change the font size using JavaScript on an input field depending on how many characters are typed. For instance, the default font size is 16px, but if I add more than 10 characters, the font size to become 12px.
HTML:
<div class="phone-input">
<input readonly="readonly" type="text" id="tocall" value="">
and css:
input#tocall {
width: 145px;
padding: 6px 3px;
color: #424242;
font-size: 16px;
border: 1px solid rgb(224, 224, 224);
font-weight: bold;
letter-spacing: 0.1em;
}
I am unfamiliar working with JavaScript so please help me.
Upvotes: 0
Views: 104
Reputation: 23416
You can do something like in the snippet below, if you just leave readonly
out of your input
, now you can't type anything into it.
var input = document.getElementById('tocall');
input.addEventListener('keyup', function (e) {
if (e.target.value.length > 10) {
e.target.style.fontSize = '12px';
} else {
e.target.style.fontSize = '16px';
}
return;
}, false);
Upvotes: 3
Reputation: 36000
Like this...
In JavaScript, access the text as
myInput = document.getElementById('tocall');
myText = myInput.value;
Then find the size of text as
len = myText.length
Now, check this value and use CSS to change font size.
if (len > 10) {
myInput.style.fontSize = "10px";
}
Upvotes: 1