Dynamic input width

Dec 18 2019, 2:33am

This has been discussed and solved before in Stackoverflow.

Let's have a look at following form which seems to have 3 input fields: inp1, inp2 and inp3.




Well actually not all of them are text input fields. If you submit this form, only inp1 and inp3 got through. The inp2 is actually a contenteditable element; it will not get through submission. One good thing about this kind of element is that it adjusts its width to its content width (try to type something to englarge / lengthen inp2 value or delete some characters and its width will automatically adjust).

The inp1 is just a regular input field of type text. The only problem with it is that -- unlike inp2 -- it doesn't have capability to adjust its width to its own changing value / content. There's currently no way to CSS style it to have this dynamic width behavior.

So the only solution is to use javascript to catch input changing value event and adjust it. And inp3 performs this quite well. See following script:

	document.querySelector('input[name="inp3"]').addEventListener('input', function(){
		this.style.width = this.value.length + 'ch';
	}, false);

Comments