Here is the simplest sample
<html>
<head>
<title>Adaptive input width sample</title>
<style type="text/css">
#meter { visibility: hidden; padding-left: 1em;
font-family: serif; font-size: 12pt; border: thick solid; }
input { padding-left: 0.5em; font-family: serif; font-size: 12pt; }
</style>
</head>
<body>
<input id="test" type="text"/><span id="meter"/>
<script>
setWidthSync(
document.getElementById("test"),
document.getElementById("meter"));
function setWidthSync(target, meter) {
var adjustWidth = function() {
meter.innerHTML = target.value;
target.style.width = meter.offsetWidth;
};
adjustWidth();
target.onkeydown = function() { adjustWidth(); };
target.onkeyup = function() { adjustWidth(); };
}
</script>
</body>
</html>
The idea is: you are using the hidden element
meter
(
span
, in my example) to measure actual width of the same text. The results can be slightly inaccurate due to different styles of the elements, so they should be kept close, via CSS style, with enough padding value for the
meter
element.
Also, this sample shows some flicker, because the modified text is rendered first, and only then the width of input is adjusted. Besides, the width is not accurately calculated, if a user inputs several blank space character in a row, because in HTML rendering such sequences are always rendered as one blank space. I'll leave improving this code for your home exercise. I hope you got the idea. :-)
—SA