How to Increase Input Box Size Dynamically using JavaScript?

The default size of a text input box in HTML is 20. Here the value 20 represents the total width of 20 characters entered into the input box.

It means that you can see at most 20 characters at a time in the input box. If you type more than 20 characters, they start shifting to the left so that you could type more characters.

But, we want to override this default behavior i.e. we want to increase the input box size dynamically as we type more characters into it.

This can be achieved in three steps:

  • Add an oninput event listener to the input and bind it to any custom function for eg. adjustWidth(). This function will be invoked every time you type something into the input box.
  • Check if the user has typed more than 20 characters into the input box, if it is so, increase the input box width by 6px every time the user inputs a character. 6px is the space occupied by a character using the standard font.
  • Set the input width to its default(initial) value if the input box is empty.

So let’s do it.

First, add the oninput event listener to the input box and bind it to the adjustWidth() function:

    <input type='text' placeholder='Type something..' oninput='adjustWidth(this);'>

Next, add the below JavaScript code in your js file:


const maxLength = 100;  // Set Max input length(100chars)

function adjustWidth(input){
        // check if input box is empty'initial';
    }else if(input.value.length>20 && input.value.length<maxLength){
        // Increase input width by 6 px on each key press
        // reserve some extra space(5*6px) for 
        // better user experience = (input.value.length*6)+(5*6) + 'px';    

We have set the maximum input width to 100. You can increase or decrease it according to your requirements.

Thanks for reading.