rsk82
rsk82

Reputation: 29407

Resize input to fit its content

I do not care for a specific technology, it could be JS, CSS or even some unstandard and evil html attributes. I just want the input to get bigger if user types over the right border.

Upvotes: 13

Views: 17941

Answers (3)

user187676
user187676

Reputation:

Let the browser do the calculating of the width by using a div with contenteditable set to true.

<div class="pseudo-input" contenteditable="true">Resizes to my content!</div>

There should be no issues with browser support http://caniuse.com/#feat=contenteditable

Upvotes: 17

You can also create div element, copy your input style to it and use it's dimensions to resize input. (Chosen multiple uses this solution).

var input = $('input'),
    dummy = $('<div style="position:absolute; left: -1000%;">').appendTo('body');

['font-size', 'font-style', 'font-weight', 'font-family',
 'line-height', 'text-transform', 'letter-spacing'].forEach(function(index) {
    dummy.css(index, input.css(index));
});

input.on('input', function() {
   dummy.html(this.value);
   input.width(dummy.width());
});

UPD: better to use pre instead div to follow spaces size.

Upvotes: 5

user113716
user113716

Reputation: 322582

Maybe someone else has a better way, but you could try this:

Example: http://jsfiddle.net/aAueA/1/

var input = document.getElementsByTagName('input')[0];

input.onkeypress = input.onkeydown = function() {
    this.size = ( this.value.length > 10 ) ? this.value.length : 10;
};

This sets it at a minimum size of 10 and expands if you go beyond 10 characters.

Probably works best with a fixed width font:

input {
    font-family:Courier;
}

Upvotes: 10

Related Questions