I managed to write an angular directive (I have extracted it to pure jQuery for this post) to auto-adjust the width of a text input.
However, it seems like the width of the input field is not changing fast enough because the contents scroll back and forth.
Type into the input field to see for yourself: Demo on JSFiddle
Here is the code:
var $element = $('#my-input');
// create dummy element to calculate text width in pixels
var dummy = $('<span></span>');
$('body').append(dummy);
dummy.css('visibility', 'hidden');
// apply all relevant text styling from our input element
dummy.css('fontFamily', $element.css('fontFamily'));
dummy.css('fontSize', $element.css('fontSize'));
dummy.css('fontWeight', $element.css('fontWeight'));
dummy.css('letterSpacing', $element.css('letterSpacing'));
var resize = function() {
dummy.html($element.val().replace(/ /g, ' '));
$element.width(dummy.innerWidth() + 1); // it's 1px off for some reason
};
resize();
$element.on('keyup', resize);
How can I prevent this from happening? I've already experimented some with scrolling the input field but to no success. Anybody have an idea?