Get input text width when typing

I see two ways.

First:

You can use a div with content editable instead input. Like this you can see the width of the div.

var elemDiv = document.getElementById('a');

elemDiv.onblur = function() {
  console.log(elemDiv.clientWidth + 'px');
}
div {
  width: auto;
  display: inline-block;
}
<div id='a' contenteditable="plaintext-only">Test</div>

Note : Like @Leon Adler say, this way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.


Second:

Use an input type text and paste the content into an invisible div. And you can see the width of the invisible div.

var elemDiv = document.getElementById('a'),
  elemInput = document.getElementById('b');

elemInput.oninput = function() {
  elemDiv.innerText = elemInput.value;
  console.log(elemDiv.clientWidth + 'px');
}
.div {
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}
<input id='b' type='text'>
<div id='a' class='div'></div>

Note : For this way, you must have the same font and font size on input and div tags.


Canvas measureText() method can be helpful in such a case. Call the following function whenever you need to get your text width:

function measureMyInputText() {
    var input = document.getElementById("txtid");
    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");
    var txtWidth = ctx.measureText(input.value).width;

    return txtWidth;
}

For more accurate result, you may set font styling to the canvas, especially if you set some font properties to the input. Use the following function to get the input font:

 function font(element) {
     var prop = ["font-style", "font-variant", "font-weight", "font-size", "font-family"];
     var font = "";
     for (var x in prop)
         font += window.getComputedStyle(element, null).getPropertyValue(prop[x]) + " ";

     return font;
 }

Then, add this line to the frist function:

ctx.font = font(input);

I have modified Chillers answer slightly, because it looks like you wanted the width rather than the letter count. I have created a span, which is absolute positioned off the screen. I am then adding the value of the input to it and then getting the width of the span. To make it more fancy you could create the span with javascript.

Note that the input and the span would have to have the same CSS styling for this to be accurate.

document.getElementById("txtid").addEventListener("keyup", function(){
  var mrspan = document.getElementById("mrspan");
  mrspan.innerText = this.value;
  console.log(mrspan.offsetWidth + "px");
});
<input type="text" id="txtid">
<span id="mrspan" style="position:absolute;left:-100%;"></span>