Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change the font size of an input text box to fill the dimensions

I'd like to change the font size into an <input type="text" size="10> dynamically to fill the box. Here are some examples:

With less chars:

enter image description here

With more chars:

enter image description here

Is it possible?

like image 764
Perocat Avatar asked May 25 '13 00:05

Perocat


People also ask

How to dynamically change the size of font size based on text?

To dynamically change the size of font size based on text length using JavaScript, we can resize the text if the height of the containing div is bigger than the div containing the text. to add the input to enter the text and the outer and inner divs. The inner div will contain the text. to select the elements with document.querySelector.

How to give width and height to HTML input text box?

Answer: By using style attribute in <input> tag you can give width and Height to HTML input text box. See the below simple example of it. Output: See the below changed width and Height to HTML input text box.

What is the default size of input field in HTML?

Size Input Text Box Using the Size attribute in the input html tag will indicating how many characters wide the input field should be. The value is numeric. Where the value must be a number greater than 0, and the default value is 20.

What happens to the textbox width when the text is cleared?

Observation: With this code, the textbox width is not returning back to normal once the text is cleared. This dynamic calculation will highly depend on font size and this is not gonna work always . Unfortunately this will only increase the size of the input. If you delete characters the size will not decrease.


2 Answers

I know JQuery and JavaScript weren't mentioned or tagged, but what you want will need JavaScript, and the JQuery.InputFit plugin will do exactly what you want:

<input type="text" name="younameit" id="input">
<script type="text/javascript">
$('input').inputfit();
</script>
like image 189
Alcides Queiroz Avatar answered Sep 29 '22 06:09

Alcides Queiroz


I'm a little late to this question, but I want offer a solution in case you don't want to implement jquery just for this:

<p>A function is triggered when the user releases a key in the input field. The function transforms the characters size.</p>
Enter your name: <input type="text" id="fname" onkeyup="myFunction()">


function myFunction(){
var x=document.getElementById("fname");
    var initialSize=25-x.value.length;
    initialSize=initialSize<=10?10:initialSize;
x.style.fontSize = initialSize + "px";
}

check out this jsfiddle

like image 34
isJustMe Avatar answered Sep 29 '22 07:09

isJustMe