How to change the Input Font Size based on Text Length

Recently I had a great conversation with an outstanding User Experience designer about a few interactions on a project we were working on. One of the points we talked about was, what should happen when text within input fields are excessively long.

The desired result we both agreed on was to change the font size of the html input field on the fly. Thankfully this is extremely easy with a little bit of jQuery that listens to events on the input field.

So if you happen to be in the same situation hopefully these snippets should get you heading down the right track.


1

First we need a simple input field with an ID or Class to hook into. I have opted for an ID in this example.


<input type="text" id="location" placeholder="Placeholder Text" />

2

Secondly a little bit of CSS to make sure the text is always aligned in the middle after it gets resized. No doubt some of this CSS will not match your designs.


#location {
  font-size: 100%;
  outline: none;
  width: 200px;
  height: 30px;
  display: table-cell; 
  vertical-align: middle;
  border: 1px solid #ccc;
}

3

Thirdly we need to get a little bit of jQuery listening to the users actions. This little snippet just checks to see if the amount of characters are below a certain length. Depending on the value it will adjust the font-size. There are many ways to achieve the same effect but for my circumstances this made sense for me.

If you would like to adjust the font-size to suit your design, just uncomment out the console.log and go crazy.


$('#location').keypress(function() {

  var textLength = $(this).val().length;

  if(textLength < 20) {
   // Do noting 
  } else if (textLength < 40) {
      $(this).css('font-size', '85%');
  } else if (textLength > 40) {
      $(this).css('font-size', '70%');
  }

 //console.log(textLength);
});

If you need to listen to more events, you can just adjust the the above snippet like so:


$('#location').on('keypress blur', function() {

......

});

4

Demo time. Just type a bunch of characters and see the result.

See the Pen cgilk by Jake Bresnehan (@jakebresnehan) on CodePen